OutputStream流写入中文乱码问题

OutputStream流写入中文乱码问题

FileOutputStream流 的 write() 方法,写入英文没有问题,中文就变乱码。 原因是该流时字节流,只能写入字节。

而在UTF-8编码中,英文、数字为1字节,汉字为3字节。

解决方案1:将写入的字符串进行编码,然后再存储即可。 编码方法:

String str = "我爱你中国";
byte[] b = str.getBytes();

【案例】将中文字符串通过OutputStream流写入到文件内

public class Demo3 {
          
   
    public static void main(String[] args) throws IOException {
          
   
        File f = new File("File/myFile.txt");
        f.createNewFile();
        OutputStream s1 = new FileOutputStream("File/myFile.txt");	
        String str = "我爱我凡";
        byte[] b = str.getBytes(StandardCharsets.UTF_8);
        for (int i = 0; i < b.length; i++) {
          
   
            s1.write(b[i]);
        }
        s1.close();
    }
}

成功写入~ 解决方法2:直接用字符流FileWriter写入,该流写入字符,一劳永逸。

经验分享 程序员 微信小程序 职场和发展