BufferedReader和BufferedWriter是InputStreamReader和OutputStreamWriter的进一步包装,用缓冲提高后两者的效率。
BufferedReader和BufferedWriter用法案例如下:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:\\idea_java\\aaa.txt")),"utf-8"));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("E:\\idea_java\\bbb.txt")),"gbk"));
char[] chars = new char[1024];
int len = 0;
while ((len=bufferedReader.read(chars))!=-1){bufferedWriter.write(chars,0,len);
}
bufferedReader.close();
bufferedWriter.close();
而BufferedInputStream和BufferedOutputStream是FileInputStream和FileOutputStream的进一步包装,同理也是为提高效率。
不过FileInputStream和FileOutputStream在文件传输时可自定义使用同一个数组,而Buffered输入输出使用两个数组,性能会略差于自定义的一个缓冲数组。
BufferedInputStream和BufferedOutputStream用法案例如下:
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(new File("E:\\idea_java\\aaa.txt")));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("E:\\idea_java\\bbb.txt"),true));
int len = 0;
byte[] bytes = new byte[1024];
while ((len=bufferedInputStream.read(bytes))!=-1){bufferedOutputStream.write(bytes,0,len);
}
bufferedInputStream.close();
bufferedOutputStream.close();
下面主要说明
BufferedReader与BufferedInputStream
以及BufferedWriter与BufferedOutputStream的使用区别
前者可以自己定义读与写的字符编码,第一块代码以utf-8读,以gbk写。(当然如果aaa.txt不是utf-8,那读出来肯定是乱码)
后者并不能自定义读与写的字符编码,第二块代码只能以字节流形式进行读写。
其根本是像InputStreamReader有字节流与字符流的转换。而像FileInputStream只有字节流读取。
还有一个地方要区分的是BufferedReader在调用read、BudderedWriter调用write所用的数组缓冲是char类型,
这也归于其字符流与字节流之间的变换。
而BufferedInputStream调用read、BufferedOutputStream调用write所用数组是byte类型,因为传输的全程是字节流。