介绍
- FileInputStream继承自抽象类 InputStream
- A FileInputStream从文件系统中的文件获取输入字节。 什么文件可用取决于主机环境。
- FileInputStream用于读取诸如图像数据的原始字节流。 要阅读字符串,请考虑使用FileReader 。
读取方式:如果达到文件的末尾, 返回 -1
代码
public static void readFile01() {
String filePath = "d:/a.txt";
FileInputStream fileInputStream = null;
int readData = 0; // 接收字节流
try {
fileInputStream = new FileInputStream(filePath);
//返回-1 表示读取完毕
while ((readData = fileInputStream.read()) != -1) {
// 注意:不同编码方式英文和中文的字节数不同,
//字节数超过1,将会发生乱码
System.out.print((char) readData); // 转成字符显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void readFile02() {
String filePath = "d:/a.txt";
FileInputStream fileInputStream = null;
byte[] buff = new byte[8]; // 接收字节流
int readLen = 0;
try {
fileInputStream = new FileInputStream(filePath);
//返回实际读入的字节个数,如果返回-1 表示读取完毕
while ((readLen = fileInputStream.read(buff)) != -1) {
System.out.print(new String(buff, 0, readLen)); // 转成字符显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}