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读取时候一般不会中文乱码


  • 相关阅读:
    POJ-1182 食物链
    P1020 导弹拦截
    牛客寒假训练营2-C算概率
    牛客寒假训练营2-H施魔法
    牛客寒假算法训练营2-建通道
    D
    C
    A
    B
    【Luogu3366】【模板】最小生成树
  • 原文地址:https://www.cnblogs.com/Hello-TomCat/p/12613480.html
Copyright © 2011-2022 走看看