Java FileInputStream用法很简单,它的作用一般用来读取文件内容,再Java I/O操作中,FileInputStream属于文件输入流,我们只需要指定文件读取即可:
String srcFile = "test.txt"; FileInputStream fin = new FileInputStream(srcFile);
直接文件读取,会抛出FileNotFoundException错误,所以我们需要使用try-catch来捕获FileInputStream文件输入流抛出的异常,代码如下:
try {
FileInputStream fin = new FileInputStream(srcFile);
}catch (FileNotFoundException e){
// The error here
}读取文件之后,我们需要关闭FileInputStream输入流
fin.close();
此时也会抛出IOException异常,所以也需要try-catch来捕获IOException异常信息,代码如下:
try {
fin.close();
}catch (IOException e) {
e.printStackTrace();
}Java FileInputStream完整用法如下:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/* 来自 www.tpyyes.com */
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();
}
}
}