Java判斷bytes編碼


<dependency>
            <groupId>com.googlecode.juniversalchardet</groupId>
            <artifactId>juniversalchardet</artifactId>
            <version>1.0.3</version>
</dependency>
    //判斷byte編碼類型
    public static String getEncoding(byte[] bytes) {
        String DEFAULT_ENCODING = "UTF-8";
        UniversalDetector detector =new UniversalDetector(null);
        detector.handleData(bytes, 0, bytes.length);
        detector.dataEnd();
        String encoding = detector.getDetectedCharset();
        detector.reset();
        if (encoding == null) {
            encoding = DEFAULT_ENCODING;
        }
        return encoding;
    }
     //此處為http獲取到的bytes
        byte[] bytes = new httppost().getdata(url,null);
        String encoding = Tools.getEncoding(bytes);//編碼判斷
        try {
            if(encoding.indexOf("GB")>=0){//由於GBK編碼有多種,此處這樣判斷即可
                result = new String(bytes,"gbk");
            }
            if("UTF-8".equals(encoding)) {
                result = new String(bytes, "utf-8");
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("抓取新ERP櫃子數量編碼失敗");
            e.printStackTrace();
        }

 


免責聲明!

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



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