Java使用FileInputStream流读取文件
FileInputStream类是一种可以从文件中读取字节的输入流,它的构造函数有两种:
- FileInputStream(String filePath):以文件路径的形式构建FileInputStream对象
- FileInputStream(File file):以文件对象的形式构建FileInputStream对象
FileInputStream类的read()方法可以读取文件中的字节,其返回值是读取的字节,如果到达文件末尾,则返回-1。
使用示例
下面给出一个使用FileInputStream类读取文件的示例:
public static void readFile(String filePath) {
FileInputStream fis = null;
try {
// 以文件路径的形式构建FileInputStream对象
fis = new FileInputStream(filePath);
// 定义一个变量存储读取到的字节
int b;
// 使用循环来读取文件中的字节
while ((b = fis.read()) != -1) {
// 打印读取到的字节
System.out.print((char) b);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭FileInputStream
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
上面的示例中,使用构造函数FileInputStream(String filePath)构建FileInputStream对象,使用read()方法读取文件中的字节,关闭FileInputStream。
使用FileInputStream类可以很方便的读取文件中的字节,只需要构造FileInputStream对象,使用read()方法即可,记得关闭FileInputStream。