缓冲区
// 带缓冲区(Buffer)的流,能够减少 IO 的读写次数,提高效率
// 带缓冲的字节流
try (FileInputStream fileInputStream = new FileInputStream("D:/JavaTest/1.txt");
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) {
// 使用完毕,无论是否产生异常,系统都会把 流 给关闭
// 不需要我们手动的关闭了
// try 后加 (),创建 流 的代码放在 () 中,如果只有一行,最后的 ; 可加可不加
// 如果要创建多个 流,添加 ; 继续再 () 中创建
// try-with-resource,自动关闭流,使用这个功能必须要求 class 实现 Closeable 接口
// BufferedInputStream 就是带缓冲区的输入流,
// 使用和 FileInputStream 一模一样
int length = 0;
byte[] bytes = new byte[6];
while ((length = bufferedInputStream.read(bytes)) != -1) {
String text = new String(bytes, 0, length);
System.out.println(text);
}
}
字符流
try (FileInputStream fileInputStream = new FileInputStream("D:/JavaTest/1.txt");) {
int length = 0;
// 数字和英文占 1 个字节
// 中文占两个字节
// 字符流,一次读取一个字符,处理文本的读写
byte[] bytes = new byte[5];
while ((length = fileInputStream.read(bytes)) != -1) {
String text = new String(bytes, 0, length);
System.out.println(text);
}
}
// Reader 和 Writer 是字符流,一次能够读写一个字符
// 都是 abstract 类型,只能使用它们的子类
// FileReader 和 FileWriter 是可用的两个子类
try (FileReader fr = new FileReader("D:/JavaTest/1.txt");) {
int length = 0;
char[] chars = new char[5];
while ((length = fr.read(chars)) != -1) {
String text = new String(chars, 0, length);
System.out.println(text);
}
}