图解转换流
package com.soar.chario;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class Demo7_TransIO {
/*
* FileReader是使用默认码表读取文件, 如果需要使用指定码表读取, 那么可以使用InputStreamReader(字节流,编码表)
* FileWriter是使用默认码表写出文件, 如果需要使用指定码表写出, 那么可以使用OutputStreamWriter(字节流,编码表)
*********************************************
BufferedReader br = //高效的用指定的编码表读
new BufferedReader(new InputStreamReader(new FileInputStream("UTF-8.txt"), "UTF-8"));
BufferedWriter bw = //高效的用指定的编码表写
new BufferedWriter(new OutputStreamWriter(new FileOutputStream("GBK.txt"), "GBK"));
int ch;
while((ch = br.read()) != -1) {
bw.write(ch);
}
br.close();
bw.close();
*/
public static void main(String[] args) throws IOException {
//defaultRead();
//requireRead();
BufferedReader br = //更高效的读
new BufferedReader(new InputStreamReader(new FileInputStream("utf-8.txt"),"utf-8"));
BufferedWriter bw = //更高效的写
new BufferedWriter(new OutputStreamWriter(new FileOutputStream("gbk.txt"),"gbk"));
int c;
while((c = br.read()) != -1){
bw.write(c);
}
br.close();
bw.close();
}
private static void requireRead() throws UnsupportedEncodingException,
FileNotFoundException, IOException {
InputStreamReader isr = new InputStreamReader(new FileInputStream("utf-8.txt"),"utf-8"); //指定码表读字符
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("gbk.txt"),"gbk"); //指定码表写字符
int c;
while((c = isr.read()) != -1){
osw.write(c);
}
isr.close();
osw.close();
}
private static void defaultRead() throws FileNotFoundException, IOException {
//用默认编码表读写,出现乱码
FileReader fr = new FileReader("utf-8.txt");
FileWriter fw = new FileWriter("gbk.txt");
int c;
while((c = fr.read()) != -1){
fw.write(c);
}
fr.close();
fw.close();
}
}