字符流读写只适用于字符文件。
基本字符流(转换流)读写文件
转换流本身是字符流,但是实例化的时候传进去的是一个字节流,所以叫做转换流
InputStreamReader isr = new InputStreamReader(new FileInputStream(inputPath), "GB2312"); OutputStreamWriter osr = new OutputStreamWriter(new FileOutputStream(outPutPath), "GB2312"); // 可以直接写入字符串/字符/字符数组等 osr.write("xxxxx "); // 单个字符读写 int c; while ((c = isr.read()) != -1) { osr.write(c); } // 字符数组读写 char[] chs = new char[1024]; int len; while ((len = isr.read(chs)) != -1) { osr.write(chs, 0, len); } osr.close(); isr.close();
简化版字符流(常用)读写文件
FileReader fr = new FileReader(inPutPath); FileWriter fw = new FileWriter(outPutPath); // 一次读写一个字符 int ch; while ((ch = fr.read()) != -1) { fw.write(ch); } // 一次读写一个字符数组 char[] chs = new char[1024]; int len; while ((len = fr.read(chs)) != -1) { fw.write(chs, 0, len); } fr.close(); fw.close();
缓冲区字符流读写文件
BufferedReader br = new BufferedReader(new FileReader(inPutPath)); BufferedWriter bw = new BufferedWriter(new FileWriter(outPutPath)); // 一次读写一个字符 int ch; while ((ch = br.read()) != -1) { bw.write(ch); } // 一次读写一个字符数组 char[] chs = new char[1024]; int len; while ((len = br.read(chs)) != -1) { bw.write(chs, 0, len); bw.newLine(); System.out.print(new String(chs, 0, len)); } // 一次读写一行数据 String line; while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); bw.flush();//刷新数据 } br.close(); bw.close();