java文件的打开与关闭
因为要想操作文件需要先学会打开和关闭文件 如果要直接读取,用请直接跳过本段
在Java I/O中,流意味着数据流。流中的数据可以是字节,字符,对象等。
要从文件读取,我们需要创建一个FileInputStream类的对象,它将表示输入流。
String srcFile = "test.txt";//文件地址
FileInputStream fin = new FileInputStream(srcFile);//引用名
如果文件不存在,FileInputStream类的构造函数将抛出FileNotFoundException异常。要处理这个异常,我们需要将你的代码放在try-catch块中,如下所示:
try {
FileInputStream fin = new FileInputStream(srcFile);
}catch (FileNotFoundException e){
// The error handling code goes here
}
最后,我们需要使用close()方法关闭输入流。
fin.close();
close()方法可能抛出一个IOException,因此,我们需要在try-catch块中包含这个调用。
try {
fin.close();
}catch (IOException e) {
e.printStackTrace();
}
通常,我们在try块中构造一个输入流,并在finally块中关闭它,以确保它在我们完成后总是关闭。
所有输入/输出流都可自动关闭。我们可以使用try-with-resources来创建它们的实例,所以无论是否抛出异常,它们都会自动关闭,避免需要显式地调用它们的close()方法。
java文件的读取
FileInputStream类有一个重载的read()方法从文件中读取数据。我们可以一次读取一个字节或多个字节。
read(int r)
这个方法从 InputStream 对象读取指定字节的数据。返回为整数值。返回下一字节数据,如果已经到结尾则返回-1。
read(byte[] r)
这个方法从输入流读取r.length长度的字节。返回读取的字节数。如果是文件结尾则返回-1。
`
文件输入流一次读取一个字节。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String dataSourceFile = "asdf.txt";
try (FileInputStream fin = new FileInputStream(dataSourceFile)) {
byte byteData;
while ((byteData = (byte) fin.read()) != -1) {
System.out.print((char) byteData);
}
} catch (FileNotFoundException e) {
;
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件输入流一次读取全部。
String file="src\\txt1.txt";
try {
FileInputStream fin = new FileInputStream(file);
byte[] a = new byte[1024];//空间可变
int n = fin.read(a); //将文件内容读取到字节数组a中
System.out.println(new String(a, 0, n));//n为无穷大
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
;
按行读取文本文件的内容
public class test3 {
//按行读取文本文件的内容
public static void readFileContent(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String readStr;
while ((readStr = reader.readLine()) != null) {
System.out.println(readStr);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public static void main(String[] args) {
readFileContent("F:\\test.txt");
}
}
如果想看底层一点的文件请看我的另一个文章
跳转

2436

被折叠的 条评论
为什么被折叠?



