Java IO流 打印流 PrintStream PrintWriter
Java IO流 序列化流 ObjectOutputStream ObjectInputStream
Java IO流 缓冲流 BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
Java IO流 字符流 目录拷贝
Java IO流 字符流 FileWriter
Java IO流 字符流 FileReader
Java IO流 字节流 FileInputStream
Java IO流 字节流 FileOutputStream
字符流的底层就是字节流
字符流 = 字节流 + 字符集
一次读一个字节,遇到中文时,一次读多个字节
创建对象
两种方式
构造函数传入路径
构造函数传入传入File对象
String filePath = "src/main/java/io_stream/a.txt";
FileReader reader = new FileReader(filePath);
FileReader fileReader = new FileReader(new File(filePath));
文件读取
FileReader 的读取方式有四种
read() 每次读取一个字节,遇到汉字就读取多个字节,GBK一次两个,UTF-8一次三个,读取到末尾返回-1
read(char cbuf[]) 将读取到的数据存入cbuf数组中
read(char cbuf[], int offset, int length) 将读取到的数据存入cbuf数组中从offset开始的连续length个位置
note:
文件中数据为 零abcdefg一二三
读取之后调用close()关闭流
public class ByteStream {
public static void main(String[] args) throws IOException {
String filePath = "src/main/java/io_stream/a.txt";
testFileReader(filePath);
}
public static void testFileReader(String filePath) throws IOException {
FileReader reader = new FileReader(filePath);
// read()测试方法 每次运行一种方法测试,其他要注释掉,以免影响结果
int b = reader.read();
System.out.println((char)b); // 零
// read(char cbuf[])测试方法 返回值为读取到的字节数量
char[] chars = new char[7];
int sum = reader.read(chars);
chars.toString();
System.out.println(sum); // 7
System.out.println(chars); // 零abcdef
// read(char cbuf[], int offset, int length)测试方法 返回值为读取到的字节数量
char[] chars = new char[7];
int sum = reader.read(chars, 0, 3);
System.out.println(sum); // 3
System.out.println(chars); // 零ab
reader.close();
}
}