1.继承关系图
首先了解一下 FileInputStream 的继承关系图,熟悉他的位置:
FileInputStream 是 InputStream 的一个子类。
2.API 介绍
字节输入流,作用就是以
字节
的为单位读取文件内容到程序中
。
/**
* 1.字节输入流读取文件 read() 方法
* 方法作用 : 按字节读入文件,每次读取一个字节的数据
* 方法返回值 : 返回读入的字节数据,如果是-1,代表读取完毕
* 注 : 1.因为是按照一个字节一个字节的方式进行读取,所以读取中文会出现乱码的情况
* 2.流在使用完毕后要关闭资源,调用close()方法
*/
/**
* 2. read(byte[] b) 方法
* 方法作用 : 按字节读入文件,每次将读取的数据放入到byte数组b中
* 方法返回值 : 返回读取到的数据的长度,如果是-1,代表读取完毕
* 注 :1.因为是一组一组的读取数据,所以可能会出现中文乱码的问题
* 2.流在使用完毕后要关闭资源,调用close()方法
*/
3.文件读取案例案例代码
3.1 读取的文件内容
文件路径 :
D:\EDailyRoutine\java-io-test\004FileInputStreamRead.txt
hello world
hello FileInputStream
hello method read
大家好 测试read()方法
3.2 read() 方法
package com.northcastle.inputStream_;
import java.io.*;
public class ApplicationFileInputStream {
public static void main(String[] args) {
//1.创建 File 对象
String filePath = "D:\\EDailyRoutine\\java-io-test\\004FileInputStreamRead.txt";
File file = new File(filePath);
//2.创建 FileInputStream 对象
FileInputStream inputStream = null;
//3.创建一个变量,接收read()方法读取到的内容
int readData = 0;
try {
inputStream = new FileInputStream(file); // 此处会抛出 FileNotFoundException
readData = inputStream.read(); // 此处会抛出 IOException
//4.循环读取文件的内容
while (readData != -1){
System.out.print((char)readData); // int --> char 转换一下
readData = inputStream.read(); // 再次读取下一个字节的数据
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 5.使用完毕后,都要关闭流
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果:
存在中文乱码的问题
,
因为一个中文字符,在UTF-8编码下占3个字节。
所以,当按照一个字节一个字节的读取方式时,中文字符被拆开了,就乱码了。
hello world
hello FileInputStream
hello method read
大家好 测试read()方法
3.3 read(byte[]) 方法
package com.northcastle.inputStream_;
import java.io.*;
public class ApplicationFileInputStream {
public static void main(String[] args) {
//1.创建 File 对象
String filePath = "D:\\EDailyRoutine\\java-io-test\\004FileInputStreamRead.txt";
File file = new File(filePath);
//2.创建 FileInputStream 对象
FileInputStream inputStream = null;
//3.创建一个变量,接收read(byte[] b)方法读取到的内容
byte[] buff = new byte[8]; // 每次读取8个字节的数据
int len = 0; // 接收每次实际读取到的数据长度
try {
inputStream = new FileInputStream(file); // 此处会抛出 FileNotFoundException
len = inputStream.read(buff); // 首次读取数据,此处会抛出 IOException
//4.循环读取数据
while (len != -1){
System.out.print(new String(buff,0,len)); // 字节数组转换成字符串输出
len = inputStream.read(buff); // 再次进行读取
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 5.使用完毕后,都要关闭流
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果:
存在中文乱码问题
因为,此时读取是按照一组一组的字节数组进行读取的,
所以汉字所占的字节非常有可能被拆开,导致读取乱码。
hello world
hello FileInputStream
hello method read
���家好 测试read()方法
4.完成
Congratulations!
You are one step closer to success!