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