zoukankan      html  css  js  c++  java
  • txt文档编码格式问题(读取和写入txt文档)

    public static String resolveCode(String path) throws Exception {
    /* String code = resolveCode(path);
    File file = new File(path);
    InputStream is = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(is, code);
    BufferedReader br = new BufferedReader(isr);*/

    InputStream inputStream = new FileInputStream(path);
    byte[] head = new byte[3];
    inputStream.read(head);
    String code = "gb2312"; //GBK
    if (head[0] == -1 && head[1] == -2 )
    code = "UTF-16";
    else if (head[0] == -2 && head[1] == -1 )
    code = "Unicode";
    else if(head[0]==-17 && head[1]==-69 && head[2] ==-65)
    code = "UTF-8";

    inputStream.close();

    System.out.println(code);
    return code;
    }


    1.上面代码获取txt文档的编码格式
    2.读取txt内容时候为防止中文乱码,设置读取时候编码格式和txt文本编码格式一致
    InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(path)), /*resolveCode(path)*/resolveCode(path));设置读取txt时候的编码格式
    3.写入txt文档编码格式
    BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (path,false),"utf-8"));//resolveCode(path)//设置格式utf-8读取时候一般不会中文乱码


  • 相关阅读:
    应用层
    传输层
    一元函数微分学
    函数、极限、连续
    网络层习题与真题
    网络层
    数据链路层习题与真题
    二、使用kubeadm部署k8s
    一、Kubernetes概述
    二、rsync文件同步
  • 原文地址:https://www.cnblogs.com/Hello-TomCat/p/12613480.html
Copyright © 2011-2022 走看看