• 获取字符串的编码、修改字符串编码


        // 获取字符串的编码
        public static String getEncoding(String str) {
            String encode = "GB2312";
            try {
                if (str.equals(new String(str.getBytes(encode), encode))) {
                    String s = encode;
                    return s;
                }
            } catch (Exception exception) {
            }
            encode = "ISO-8859-1";
            try {
                if (str.equals(new String(str.getBytes(encode), encode))) {
                    String s1 = encode;
                    return s1;
                }
            } catch (Exception exception1) {
            }
            encode = "UTF-8";
            try {
                if (str.equals(new String(str.getBytes(encode), encode))) {
                    String s2 = encode;
                    return s2;
                }
            } catch (Exception exception2) {
            }
            encode = "GBK";
            try {
                if (str.equals(new String(str.getBytes(encode), encode))) {
                    String s3 = encode;
                    return s3;
                }
            } catch (Exception exception3) {
            }
            return "";
        }
    2.将字符串编码转为指定编码,如转为gbk
    public String changEncod(){String str}{
        String fileDir = "d:/str.txt";

        String str = txt2String(fileDir);

        //获取原编码
        String encod = getEncoding(str);

        //转为gbk
        String s = new String(str.getBytes(encod),"gbk");

    }
    3.获取字符串内容

    public static String txt2String(String filePath) {
    File file = new File(filePath);
    StringBuilder result = new StringBuilder();
    try {
    BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
    String s = null;
    while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
    result.append(System.lineSeparator() + s);
    }
    br.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return result.toString();
    }

     

    //改字符串编码
    public static String changeCharset(String str, String newCharset)
    throws UnsupportedEncodingException {
    if (str != null) {
    // 用默认字符编码解码字符串。
    byte[] bs = str.getBytes();
    // 用新的字符编码生成字符串
    return new String(bs, newCharset);
    }
    return null;
    }

     
  • 相关阅读:
    获取txt文件的内容
    MAT(Memory Analyzer Tool)下载和安装
    转换流:指定编码 读取文本文件InputStreamReader和写出文本文件OutputStreamWriter 字符集
    切入点表达式
    并发时事务引发的问题和事务的隔离级别
    多线程之join方法
    多线程之守护线程
    约束:主键、非空、唯一、外键
    数据库设计
    PLSQL过期解决办法
  • 原文地址:https://www.cnblogs.com/xyzq/p/7095025.html
Copyright © 2020-2023  润新知