2021-09-21 IO流(转换流的字符编码)

2021-10-17  本文已影响0人  Denholm
clipboard.png
clipboard.png
clipboard.png
clipboard.png
import java.io.*;

public class EncodeStreamDemo {

    public static void main(String[] args) throws Exception {
        writeText();
        readText();
    }

    public static void readText() throws Exception {
        InputStreamReader isr1 = new InputStreamReader(
                new FileInputStream("E:\\gbk.txt"), "GBK");
        char[] buf1 = new char[10];
        int len1 = isr1.read(buf1);
        String s1 = new String(buf1, 0, len1);
        System.out.println(s1);
        isr1.close();

        InputStreamReader isr2 = new InputStreamReader(
                new FileInputStream("E:\\utf.txt"), "UTF-8");
        char[] buf2 = new char[10];
        int len2 = isr2.read(buf2);
        String s2 = new String(buf2, 0, len2);
        System.out.println(s2);
        isr1.close();
    }

    public static void writeText() throws Exception {
        OutputStreamWriter osw1 = new OutputStreamWriter(
                new FileOutputStream("E:\\gbk.txt"), "GBK");
        osw1.write("你好");
        osw1.close();

        OutputStreamWriter osw2 = new OutputStreamWriter(
                new FileOutputStream("E:\\utf.txt"), "UTF-8");
        osw2.write("你好");
        osw2.close();
    }

}
上一篇下一篇

猜你喜欢

热点阅读