java:IO流(使用指定的码表读写字符)

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_24644517/article/details/83992105
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 {

	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();
	}

	private 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();
	}

	private 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();
	}

}

猜你喜欢

转载自blog.csdn.net/qq_24644517/article/details/83992105