java IO流之四 使用转换流InputStreamReader和OutputStreamWriter

当字节流和字符流之间需要转化的时候,或者要对字节数据进行编码转换的时候,就需要使用转换流

package org.example.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class TestStreamReader {

    public static void main(String[] args) throws Exception {
        File file = new File("E:\\b.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), "GBK");
        out.write("hello world,你好世界");
        out.close();

        InputStreamReader in = new InputStreamReader(new FileInputStream(file), "gbk");
        char[] cc = new char[1024];
        int n = 0;
        String str = "";
        while ((n = in.read(cc)) != -1) {
            str += new String(cc, 0, n);
        }
        in.close();
        System.out.println(str);
    }

}


你可能感兴趣的:(java,IO流)