字节字符转换流 java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码) 文件是byte byte byte...的数据序列 文本文件是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储序列 3)字符流(Reader Writer) 字符的处理,一次处理一个字符 字符流的基本实现 InputStreamReader 完成byte流解析为char流,按照编码解析 OutputStreamWriter 提供char流到byte流,按照编码处理
package com.xiaolu.www; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class IsrAndOswDemo { public static void main(String[] args) throws IOException { FileInputStream in = new FileInputStream("G:\\JavaProject\\IoDemo\\file.txt"); FileOutputStream out = new FileOutputStream("demo//test2.txt"); InputStreamReader isr = new InputStreamReader(in); //默认项目的编码 OutputStreamWriter osw = new OutputStreamWriter(out); int c; char[] buf = new char[8*1024]; /* * 批量读取,放入buf字符数组,从第0个位置开始放置,最多放到buf.length * 返回的是读到的字符的个数 */ while((c=isr.read())!=-1) { System.out.print((char)c); } while((c=isr.read(buf, 0, buf.length))!=-1) { String string = new String(buf, 0, c); osw.write(string); osw.flush(); } isr.close(); } }
字符流的过滤器 BufferedReader ---->readline 一次读一行 BufferedWriter/PrintWriter --->一次写一行
package com.xiaolu.www; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class BrAndBwOrPwDemo { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream("G:\\JavaProject\\IoDemo\\file.txt"))); // BufferedWriter bw = new BufferedWriter( // new OutputStreamWriter( // new FileOutputStream("demo//test3.txt"))); PrintWriter pw = new PrintWriter("demo//test4.txt"); String line; while((line=br.readLine())!=null) { System.out.println(line); // bw.write(line); //一次读一行,不能识别换行 // bw.newLine(); // bw.flush(); pw.println(line); } br.close(); // bw.close(); pw.close(); } }