40、使用字节流读取文件乱码问题

写出中文

向txt文件中写出中文,通过下面代码的演示,因为一个中文占2个字节,所以按照字节写出中文时会出现乱码的情况。

package com.sutaoyu.IO;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class IO_test_6 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream("word.txt");
            String msg = "好好学习";
            //fos.write(msg.getBytes());
            //每次写出3个字节,因为一个中文占用2个字节,所以导致乱码
            fos.write(msg.getBytes(),0,3);
            //换行
            fos.write("
".getBytes());
            fos.write("天天向上".getBytes());
            fos.flush();
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}

读取中文

从txt文件中读取文件,下面代码也出现了乱码问题

package com.sutaoyu.IO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class IO_test_7 {
    public static void main(String args) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("word.txt");
            byte[] arr = new byte[3];
            int temp;
            while((temp = fis.read(arr)) != -1) {
                System.out.println(new String(arr,0,temp));
            }    
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/10143010.html