IO- 练习:用指定的编码表将数据存至文件,再用对应的编码表读取内容输出至控制台
- import java.io.*;
- class CharSetDemo
- {
- public static void main(String[] args) throws IOException
- {
- String charSet = "GBK";
- String charSet1 = "UTF-8";
- //建立读取转换流,指定编码表
- InputStreamReader ins = new InputStreamReader(new FileInputStream("utf.txt"),charSet);
- InputStreamReader ins1 = new InputStreamReader(new FileInputStream("gbk.txt"),charSet1);
- //缓冲
- BufferedReader bufin = new BufferedReader(ins);
- BufferedReader bufin1 = new BufferedReader(ins1);
- //建立输出转换流
- BufferedWriter bufo1 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("utf.txt"),charSet));//utf-8输出
- BufferedWriter bufo = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("gbk.txt"),charSet1));//gbk输出
-
- bufo.write("我是用GBK编码的");
- bufo1.write("我是用utf-8编码的");
- bufo.close();
- bufo1.close();
- int by = 0;
- //读取utf.txt文件输出到控制台
- while((by=bufin.read())!=-1)
- {
- System.out.print((char)by);
- }
- System.out.println();//换行
- //读取gbk.txt文件输出到控制台
- while((by=bufin1.read())!=-1)
- {
- System.out.print((char)by);
- }
- System.out.println();
- bufin.close();
- System.out.println("Hello World!");
- }
- }
复制代码
|
|