字节缓冲流:在字节流和的基础上增加一个缓冲区
-
可以一次操作大量数据
-
底层有一个默认为8192字节大小缓冲区
-
需要底层流InputStream,OutputStream支持
-
可以自定义缓冲区大小
-
会自动关闭底层流
package com.li.changGe.ioStream.byteStream;
import java.io.*;
public class BufferedInputOutputStreamDemo01 {
private static String fileName = "C:\\Users\\林木\\Desktop/test.txt";
private static String fileName1 = "C:\\Users\\林木\\Desktop/test1.txt";
public static void main(String[] args) throws Exception{
bufferedInputStreamTest();
bufferedOutputStreamTest();
}
//--------------------------------------------------------------
public static void bufferedInputStreamTest() throws Exception{
InputStream inputStream = new FileInputStream(fileName);
/**
* 自定义缓冲区大小为1024
*/
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream,1024);
/**
* 我们也可以用自己的缓冲区
*/
byte[] bytes = new byte[102];
int count;
while ((count = bufferedInputStream.read(bytes)) != -1){
//O ever youthful,O ever weeping.Hello world!
System.out.println(new String(bytes,0,count));
}
//会自动关闭底层流
bufferedInputStream.close();
}
//----------------------------------------------------------------
public static void bufferedOutputStreamTest() throws Exception{
/**
* 是否追加由底层流决定
*/
FileOutputStream fileOutputStream = new FileOutputStream(fileName,true);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
//-----------------------------------------------------------------
/**
* Windows中的换行是\r\n
*/
String message = "I'm LiChangGe.\r\n";
for (int i = 0; i < 10; i++) {
bufferedOutputStream.write(message.getBytes(),0,message.length());
/**
* 是先将数据传输到缓冲区
*
* 真正到达文件还需要刷新flush()一下
* 最好写一次刷新一次
*/
bufferedOutputStream.flush();
}
System.out.println("写入完毕");
//-----------------------------------------------------------------
/**
* 关闭时Buffered也会自动刷新flush()
*/
bufferedOutputStream.close();
}
}