獲取字符串的編碼、修改字符串編碼


    // 獲取字符串的編碼
    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;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM