/**
缓存的目的:
解决在写入文件操作时,频繁的操作文件所带来的性能低的问题。
BufferedOutputStream【字节输出缓存流】内部默认的大小是8KB,每次写入时先存储到缓存中的byte数组中,当数组存满时会把数组中的数据写入文件,并且缓存下标归零。也可以传默认的大小参数。
BufferedInputStream 【字节输入缓存流】内部默认的大小是8KB,每次读取时先存储到缓存中的bytes数组中
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class BufferDemo {
public static void main(String[] args) {
ByteWrite();
ByteReader();
}
//字节输出流缓冲流的实现:
public static void ByteWrite() {
File files = new File("E:\\Java_IO\\haha.txt");
try {
OutputStream out = new FileOutputStream(files);
//构造一个字节缓冲流
BufferedOutputStream bos = new BufferedOutputStream(out);
String info = "小小哈哈啦啦";
bos.write(info.getBytes());
bos.close(); //关闭流要从内部开始关闭
//out.close(); //外层的关闭流可以不用写,try语句会自动帮我们关闭,可以看源码的实现
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//字节输入流缓冲流的实现:
public static void ByteReader() {
File files = new File("E:\\Java_IO\\haha.txt");
try {
InputStream in = new FileInputStream(files);
//构造一个字节缓冲流
BufferedInputStream bis = new BufferedInputStream(in);
byte[] bytes = new byte[1024];
int len = -1;
StringBuilder buf = new StringBuilder();
while((len=bis.read(bytes))!=-1) {
buf.append(new String(bytes,0,len));
}
bis.close();
System.out.println(buf);
//in.close(); //外层的关闭流可以不用写,try语句会自动帮助我们关闭,可以看源码的实现
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//如下是对try语句的新语法的实现,就bis.close()也不同写,try语句会自动帮助实现关闭流try(;;)里面可以写多句
//前提是try()语句里的类必须自动实现closeable()方法才行,可以看源码的实现
public static void ByteReader2() {
File files = new File("E:\\Java_IO\\haha.txt");
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(files))) {
byte[] bytes = new byte[1024];
int len = -1;
StringBuilder buf = new StringBuilder();
while((len=bis.read(bytes))!=-1) {
buf.append(new String(bytes,0,len));
}
//bis.close();
System.out.println(buf);
//in.close(); //外层的关闭流可以不用写,try语句会自动帮助我们关闭,可以看源码的实现
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
IO_File类使用:字节缓冲流
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 递归 递归方法定义中调用方法本身的现象递归解决问题的思想做递归要写一个方法找到出口条件找到规律递归的注意事项递归一...