在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
}
FileInputStream类有一个重载的read()方法从文件中读取数据。我们可以一次读取一个字节或多个字节。
read()方法的返回类型是int,虽然它返回一个字节值。如果到达文件的结尾,则返回-1。
我们需要将返回的int值转换为一个字节,以便从文件中读取字节。通常,我们在循环中一次读取一个字节。
最后,我们需要使用close()方法关闭输入流。
// Close the input stream
fin.close();
close()方法可能抛出一个IOException,因此,我们需要在try-catch块中包含这个调用。
try {
fin.close();
}catch (IOException e) {
e.printStackTrace();
}
通常,我们在try块中构造一个输入流,并在finally块中关闭它,以确保它在我们完成后总是关闭。
所有输入/输出流都可自动关闭。我们可以使用try-with-resources来创建它们的实例,所以无论是否抛出异常,它们都会自动关闭,避免需要显式地调用它们的close()方法。
以下代码显示使用try-with-resources创建文件输入流:
String srcFile = "test.txt";
try (FileInputStream fin = new FileInputStream(srcFile)) {
// Use fin to read data from the file here
}
catch (FileNotFoundException e) {
// Handle the exception here
}
以下代码显示了如何从文件输入流一次读取一个字节。
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();
}
}
}
© 著作权归作者所有