zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    设计模式学习——单例模式
    设计模式六大原则
    OIDC in Angular 6
    Angualr6访问API
    Angular6项目搭建
    Springboot 文件上传(带进度条)
    Oracle同义词(synonym)
    hexo从零开始到搭建完整
    Spring Security验证流程剖析及自定义验证方法
    Java设计模式-工厂方法模式(Factory Method)
  • 原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/10143010.html
Copyright © 2011-2022 走看看