CharasetCheck.java 1.4 KB
package com.sy.utils;


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class CharasetCheck {



    public static  String chechUTF8(String path){
        File file = new File(path);
        String str = null;
        try{
           str = FileUtils.readFileToString(file,"GB2312");
         //  str = getUTF8String(str);
        }catch (IOException e){
            e.printStackTrace();
        }
        return str;
    }
    public static String getUTF8String(String gbkStr) {
        try {
            return new String(getUTF8Bytes(gbkStr), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new InternalError();
        }
    }

    public static byte[] getUTF8Bytes(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }
}