网上有很多地方说inputStreamReader和outStreamWriter、BufferedReader和BufferedWriter都是字符流。不过也有地方说inputStreamReader和outStreamWriter只是转换流,实现字节流到字符流的转换。
而在我看来,两种说法都有道理,如果一定要分个高下的话,那就更加趋向于认同前一种。
因为只要和FileInputStream做一个简单的比较就可以知道inputSteamReader是按字符读取的,而FileInputStream是按字节。
测试部分代码如下:
1、
File file = new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest1.txt");
// 创建一个fileInputStream对象
FileInputStream fileInputStream = new FileInputStream(file);
// 获取文件中字符的长度
int leng = fileInputStream.available();
for (int i = 0; i < leng; i++) {
// 读取每个字节
System.out.print(fileInputStream.read());
System.out.println();
}
2、
File file = new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest1.txt")
// 创建字符输入流的同时指定字符集
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
while (isr.ready()) {
System.out.print(isr.read());
System.out.println();
}
在上边的例子中可以看到,对于同一个文件,FileInputStream的输出行数要比 InputStreamReader的输出行数多出两倍多(中英文混合),InputStreamReader的输出行数刚好就是文件中的字符个数。
不过,说inputStreamReader和outStreamWriter是转换流,也不是没有道理,因为通常使用的时候都是结合BufferedReader和BufferedWriter来一起使用的,inputStreamReader和outStreamWriter创建的时候可以声明字符集。
简单的示例如下:
/**
* inputStreamReader和outStreamWriter字符输入输出流
*
* @author:tuzongxun
* @Title: inAndOutTest
* @param @throws IOException
* @return void
* @date Jul 20, 2016 11:17:05 AM
* @throws
*/
public static void readAndWriterTest1() throws IOException {
File file = new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest1.txt");
File file1 = new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest2.txt");
// 创建字符输入流的同时指定字符集
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file1), "utf-8");
while (isr.ready()) {
int in = isr.read();
osw.write(in);
}
osw.flush();
isr.close();
osw.close();
}
/**
* BufferedReader和BufferedWriter 字符缓冲输入和输出流
*
* @author:tuzongxun
* @Title: readAndWriterTest2
* @param @throws IOException
* @return void
* @date Jul 21, 2016 10:36:28 AM
* @throws
*/
public static void readAndWriterTest2() throws IOException {
File file = new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest1.txt");
File file1 = new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest2.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file1), "utf-8")));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
bw.write(str);
}
bw.flush();
br.close();
bw.close();
}