/**
* ClassName: 字节缓存流
* 为了解决在写入文件操作时,频繁的操作文件所带来的性能降低的问题
* BufferedOutputStream 内部默认的缓存大小时8kb,每次写入时存储到的缓存中的byte数组中,当数组存满 时,会把数组中的数据写入文件,
* 并且缓存下标归零
* @Description: TODO
* @author cai
* @date 2018年10月17日
*/
public class BufferStreamDemo {
/*
* 读入内存的字节缓存流写法
*/
private static void byteReader() {
File file = new File("C:\\Users\\Desktop\\需要被删的\\新建文本文档 (4).txt");
InputStream in;
try {
in = new FileInputStream(file);
//构造一个字节缓冲流
BufferedInputStream bis = new BufferedInputStream(in);
byte[] bytes = new byte[2048];
int len = -1;
while((len=bis.read(bytes)) != -1) {
System.out.println(new String(bytes,0,len));
}
bis.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 读入内存的字节缓存流,代码少一些,以及会自动关闭的写法
*/
private static void byteReader2() {
File file = new File("C:\\Users\\Desktop\\需要被删的\\新建文本文档 (4).txt");
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){
byte[] bytes = new byte[2048];
int len = -1;
while((len=bis.read(bytes)) != -1) {
System.out.println(new String(bytes,0,len));
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 写出文件的字节缓存流
*/
private static void byteWriter() {
File file = new File("C:\\Users\\Desktop\\需要被删的\\新建文本文档 (4).txt");
try {
OutputStream out = new FileOutputStream(file);
//构造一个字节缓冲流
BufferedOutputStream bos = new BufferedOutputStream(out);
//
String info = "牛奶君";
out.write(info.getBytes());
bos.close();
//out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
byteWriter();
byteReader();
}
}