写出中文

向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("\r\n".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();
        }
    }
}

 

相关文章:

  • 2021-10-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-21
  • 2022-01-18
猜你喜欢
  • 2021-05-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-20
相关资源
相似解决方案