1. 编码问题
java使用utf-16be编码
2. 认识文本和文本文件
java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码)
文件是byte byte byte ...的数据序列
文本文件是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储结果
3. 字符流(Reader Writer)—->操作的是文本文本文件
字符的处理,一次处理一个字符
字符的底层仍然是基本的字节序列
字符流的基本实现
InputStreamReader 完成byte流解析为char流,按照编码解析
OutputStreamWriter 提供char流到byte流,按照编码处理
FileReader/FileWriter 对文件的操作
字符字节流转化代码:
package com.sample.io;
import java.io.FileInputStream;
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("e:\\javaio\\demoutf8.txt");
InputStreamReader isr = new InputStreamReader(in,"utf-8");
FileOutputStream out = new FileOutputStream("e:\\javaio\\demoutf81.txt");
OutputStreamWriter osw = new OutputStreamWriter(out,"utf-8");
int c ;
while((c = isr.read())!=-1){
System.out.print((char)c);
}
char[] buffer = new char[8*1024];
int c;
while(( c = isr.read(buffer,0,buffer.length))!=-1){
String s = new String(buffer,0,c);
System.out.print(s);
osw.write(buffer,0,c);
osw.flush();
}
isr.close();
osw.close();
}
}
字符流文件读写代码:
package com.sample.io;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FrAndFwDemo {
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("e:\\javaio\\demo.txt");
FileWriter fw = new FileWriter("e:\\javaio\\demo2.txt");
char[] buffer = new char[2056];
int c ;
while((c = fr.read(buffer,0,buffer.length))!=-1){
fw.write(buffer,0,c);
fw.flush();
}
fr.close();
fw.close();
}
}
4. 字符流的过滤器
BufferedReader ---->readLine 一次读一行
BufferedWriter/PrintWriter ---->写一行
代码示例:
package com.sample.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
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("e:\\javaio\\demo.txt")));
PrintWriter pw = new PrintWriter("e:\\javaio\\demo4.txt");
String line ;
while((line = br.readLine())!=null){
System.out.println(line);
pw.println(line);
pw.flush();
}
br.close();
pw.close();
}
}