package demo.io;
import java.io.*;
class 转换流OutputStreamWriter_Reader指定字符集写入和读取文本 {
public static void main(String[] args) {
assignWriter();//指定字符集写入
assignRead();//指定字符集读取
}
//指定字符集读取
private static void assignRead() {
FileReader fr = null;//方法1 doc下默认读取gbk
InputStreamReader isr = null;//方法2 指定
try {
//方法1
fr = new FileReader("gbk.txt");//实际编译器读取utf8
char[] buf = new char[1024];
int len = fr.read(buf);
System.out.println(new String(buf, 0, len));
//方法2 指定字符集读取
isr = new InputStreamReader(new FileInputStream("utf8.txt"), "utf8");
len = isr.read(buf);
System.out.println(new String(buf, 0, len));
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fr != null)
fr.close();
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//指定字符集写入
private static void assignWriter() {//两种方法等效 FileWriter中就是封装了OutputStreamWriter
FileWriter fw = null;//方法1 默认
OutputStreamWriter osw = null;//方法2 指定
try {
//方法1
fw = new FileWriter("gbk.txt");//默认gbk(doc下的jvm) 用编译器的话已经设置成utf8了
fw.write("你好");
fw.flush();
//方法2
osw = new OutputStreamWriter(new FileOutputStream("utf8.txt"), "utf-8");
osw.write("你好");
osw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (osw != null)
osw.close();
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
-
什么时候使用转换流呢?
1,源或者目的对应的设备是字节流,但是操作的却是!文本数据!,可以使用转换作为桥梁。提高对文本操作的便捷。
2,一旦操作文本涉及到具体的指定编码表时,必须使用转换流OutputStreamWriter InputStreamReader -
读取GBK流对应文件,可以用字符数组储存,在写入UTF-8流对应文件中去
*/