使用指定的码表读写字符
-
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();
package com.heima.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 Demo07_TransIO {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//demo1();
//demo2();
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();
}
public static void demo2() 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();
}
public static void demo1() 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();
}
}
来源:CSDN
作者:左绍骏
链接:https://blog.csdn.net/LeoZuosj/article/details/104091803