字符流的出现为了方便操作字符,但更重要的是加入了编码转换。
通过子类转换流来完成:
InputStreamReader
OutputStreamWriter
在两个对象进行构造的时候可以加入字符集:
InputStreamReader(InputStream in, String charsetName):创建使用指定字符集的 InputStreamReader。
OutputStreamWriter(OutputStream out, String charsetName):创建使用指定字符集的 OutputStreamWriter。
示例
import java.io.*;
class EncodeStream{
public static void main(String[] args)throws IOException{
// writeText();
readText();
}
// 使用指定字符集读取数据
public static void readText()throws IOException{
InputStreamReader isr=new InputStreamReader(new FileInputStream("gbk.txt"),"GBK"); // utf.txt UTF-8
char[] buf=new char[10];
int len=isr.read(buf);
String str=new String(buf,0,len);
System.out.println(str);
isr.close();
}
// 使用指定字符集写入数据
public static void writeText()throws IOException{
OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("gbk.txt"),"GBK"); // gbk.txt GBK
osw.write("你好");
osw.close();
}
}