• 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();
            }
        }
    }
  • 相关阅读:
    Python3学习之路~0 目录
    HIVE简单操作
    HIVE的安装
    mysql在linux上的安装
    BZOJ 1085(IDA*)
    Codeforces 916E(思维+dfs序+线段树+LCA)
    Codeforces 396C (DFS序+线段树)
    Codeforces 609E (Kruskal求最小生成树+树上倍增求LCA)
    Codeforces 191C (LCA+树上差分算法)
    POJ 1905 题解(二分+几何)
  • 原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/10143010.html
Copyright © 2020-2023  润新知