- 编码问题
- 认识文本和文本文件 java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码)
文件是byte byte byte …的数据序列
文本文件是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储结果 - 字符流(Reader Writer)---->操作的是文本文本文件
字符的处理,一次处理一个字符
字符的底层任然是基本的字节序列
字符流的基本实现
InputStreamReader 完成byte流解析为char流,按照编码解析
OutputStreamWriter 提供char流到byte流,按照编码处理
FileReader/FileWriter - 字符流的过滤器
BufferedReader ---->readLine 一次读一行
BufferedWriter/PrintWriter ---->写一行
字节字符转换流
public class IsrAndOswDemo {
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream("E:\\java学校\\Volume.java");
InputStreamReader isr = new InputStreamReader(fis,"utf-8");
FileOutputStream fos = new FileOutputStream("E:\\java学校\\Volume2.java");
OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
char[] chars = new char[8*1024];
int c;
while((c=isr.read(chars,0,chars.length)) != -1) {
String s = new String(chars,0,c);
System.out.println(s);
osw.write(chars,0,c);
osw.flush();
}
isr.close();
osw.close();
}
}
字符流只文件读写流
public class FrAndFwDemo {
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("E:\\java学校\\Volume.java");
FileWriter fw = new FileWriter("E:\\java学校\\Volume3.java");
char[] chars = new char[2056];
int c;
while((c = fr.read(chars,0,chars.length)) != -1) {
fw.write(chars, 0, c);
fw.flush();
}
fr.close();
fw.close();
}
}
字符流的过滤器
public class BrAndBwOrPwDemo {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream("E:\\java学校\\Volume.java")));
PrintWriter pw = new PrintWriter("E:\\java学校\\Volume4.java");
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
pw.println(s);
}
br.close();
pw.close();
}
}