缓冲流
创建BufferedInputStream时,将创建一个内部缓冲区数组。当读取或跳过流中的字节时,根据需要从包含的输入流中重新填充内部缓冲区,每次填充多个字节。
一、BufferedInputStream
/*
* BufferedInputStream
* 缓冲流,是包装流,创建对象的时候,传入的参数不是文件地址,而是文件流对象
* 和FileInputStream基本一致,效率相比提高
* 作用:把每次读入的数据存入到一个缓冲区,然后一次写入
* 把输出的数据存入到一个缓冲区,然后一次写出
* 如果缓冲流关闭,传入的文件流对象也会被关闭
* BufferedInputStream,BufferedOutputStream,BufferedReader,BufferedWriter
* 针对字符操作,提供了两个新方法
* readLine():读一行,返回值是所读这一行的数据。达到文件末尾,返回null
* newLine():换行。相当于\n
* 特点:
* 为了提高效率而存在,减少物理读取次数
* 提供针对字符操作的新方法
* */
public class _01_BufferedInputStream {
public static void main(String[] args) {
try (
// 创建字节输入流
FileInputStream fis = new FileInputStream(
"./SE/src/com/tianl/IO/_01_FileInputStream/_03_IO_FileInputStream.java");
// 创建字节输入缓冲流
BufferedInputStream bis = new BufferedInputStream(fis)
){
// 读取下一个字节,到达末尾返回-1
System.out.println((char) bis.read());
// 读取一个数组字节,返回读取到的长度,到达末尾返回-1
byte[] bytes = new byte[10];
int temp = bis.read(bytes);
System.out.println(new String(bytes,0,temp));
} catch (Exception e){
e.printStackTrace();
}
}
}
二、BufferedOutputStream
/*
* BufferedOutputStream
* 和FileOutputStream基本一致
* */
public class _02_BufferedOutputStream {
public static void main(String[] args) {
try (
// 创建字节输出流对象
FileOutputStream fos = new FileOutputStream(
"D:/111.txt");
// 创建字节输出缓冲流对象,并把字节输出流传入
BufferedOutputStream bos = new BufferedOutputStream(fos)
){
// 写出单个
bos.write(65);
// 写出一个数组字节
byte[] bytes = "啊啊啊啊啊啊".getBytes(StandardCharsets.UTF_8);
bos.write(bytes);
// 刷缓存
bos.flush();
} catch (Exception e){
e.printStackTrace();
}
}
}
三、BufferedReader
/*
* 字符输入缓冲流
* */
public class _03_BufferedReader {
public static void main(String[] args) {
try (
// 创建字符输入流
FileReader fr = new FileReader(
"./SE/src/com/tianl/IO/_01_FileInputStream/_03_IO_FileInputStream.java");
// 创建字符输入缓冲流,并传入
BufferedReader br = new BufferedReader(fr)
){
// 读取下一行,到达末尾返回null
System.out.println(br.readLine());
// 也可以读取一个数组字符,返回读取到的长度,到达末尾返回-1
// 空行是 \n ,两个字符
char[] chars = new char[1024];
int temp;
while ((temp=br.read(chars))!=-1){
System.out.println(new String(chars,0,temp));
}
// 循环读取行,在26行使用字符数组读取时候,文件已经读到末尾,此时再使用下面语句时swp=null
System.out.println("----------------------");
String swp;
while ((swp=br.readLine())!=null){
System.out.println(swp);
System.out.println(swp);
}
} catch (Exception e){
e.printStackTrace();
}
}
}
三、BufferedWriter
public class _04_BufferedWriter {
public static void main(String[] args) {
// 默认覆盖写入
try (FileWriter fw = new FileWriter("D:/111.txt");
// 创建字符输出缓冲流对象,并把字节输出流传入
BufferedWriter bw = new BufferedWriter(fw)){
// \n 是换行
bw.write("今天天气好吗?\n");
// 输出换行
bw.newLine();
char[] chars = {'a','b','c','d'};
bw.write(chars);
// 刷缓存
bw.flush();
} catch (Exception e){
e.printStackTrace();
}
}
}