文件编码检测.测试代码

ZC:这个是在 G转SVG的C++项目中要用到这个功能的,然后逐步查资料查到 jchardet的,相关的文章为“文件编码检测.ZC一些资料(包含java的) - CppSkill - 博客园.html(https://www.cnblogs.com/cppskill/p/9906599.html)”

ZC:相关文件位于:“..C_IDEJava_3rdC_文件编码自动检测jchardet-1.1.zip”,jar 位于 “...C_IDEJava_3rdC_文件编码自动检测jchardet-1.1distlibchardet.jar

1、测试代码:

 (1)、字符集编码的自动识别jchardet - 云守护的专栏 - CSDN博客.html(https://blog.csdn.net/earbao/article/details/38709701

  (1.1)、

package com.AAA;

import java.io.BufferedInputStream;
import java.net.URL;
 
import org.mozilla.intl.chardet.HtmlCharsetDetector;
import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import org.mozilla.intl.chardet.nsPSMDetector;
 
public class FFF
{ 
    public static void main(String[] args) throws Exception
    {
        String strUrl = "C:\Users\33\Desktop\zzz.g";
        int lang = nsPSMDetector.ALL;
//        if (args.length < 1) {
//            System.out.println("usage:Main url <int>lang");
//            return;
//        }
//        int lang = (args.length == 2) ? Integer.parseInt(args[1])
//                : nsPSMDetector.ALL;
        // 实现nsICharsetDetectionObserver接口,这个接口只有一个Notify()方法.
        // 当jchardet引擎自己认为已经识别出字符串的字符集后(不论识别的对错),都会调用这个Notify方法。
        nsICharsetDetectionObserver cdo = new nsICharsetDetectionObserver() {
            public void Notify(String charset) {
                HtmlCharsetDetector.found = true;
                System.out.println("CHARSET = " + charset);
            }
        };
        /**
         * 初始化nsDetector() lang为一个整数,用以提示语言线索,可以提供的语言线索有以下几个: Japanese Chinese
         * Simplified Chinese Traditional Chinese Korean Dont know (默认)
         */
        nsDetector det = new nsDetector(lang);
        // 设置一个Oberver
        det.Init(cdo);
        //URL url = new URL(args[0]);
        URL url = new URL(strUrl);
        BufferedInputStream imp = new BufferedInputStream(url.openStream());
        byte[] buf = new byte[1024];
        boolean done = false; // 是否已经确定某种字符集
        boolean isAscii = true;// 假定当前的串是ASCII编码
        int len;
        boolean found = false;
        while ((len = imp.read(buf, 0, buf.length)) != -1) {
            // 检查是不是全是ascii字符,当有一个字符不是ASC编码时,则所有的数据即不是ASCII编码了。
            if (isAscii)
                isAscii = det.isAscii(buf, len);
            // 如果不是ascii字符,则调用DoIt方法.
            if (!isAscii && !done)
                done = det.DoIt(buf, len, false);// 如果不是ASCII,又还没确定编码集,则继续检测。
        }
        det.DataEnd();// 最后要调用此方法,此时,Notify被调用。
        if (isAscii) {
            System.out.println("CHARSET = ASCII");
            found = true;
        }
        if (!found) {// 如果没找到,则找到最可能的那些字符集
            String prob[] = det.getProbableCharsets();
            for (int i = 0; i < prob.length; i++) {
                System.out.println("Probable Charset = " + prob[i]);
            }
        }
    }
 
}

 (2)、jChardet探测文件字符编码-博客-云栖社区-阿里云.html(https://yq.aliyun.com/articles/59514

      ZC:这里的代码,在检测 D:DRGISBINGraphics里面的图形时,若 文件是 UTF-8编码的,则它显示是 ASCII;若文件是 UTF-8 + BOM编码的,则它显示是 UTF8.看起来 不太准...

  (2.1)、

package com.AAA;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
// jChardet 火狐所用字符编码检测算法
public class FileCharsetDetector {
    private boolean found = false;
    private String encoding = null;

    public static void main(String[] argv) throws Exception
    {
        //File file1 = new File("C:\Users\Administrator\Desktop\VideoViewDemo\VideoViewDemo\src\org\apache\android\media\AudioPlayer.java");
        //File file1 = new File("C:\Users\33\Desktop\zzz.g");
//        File file1 = new File("D:\DRGIS\BIN\Graphics\35kV娄宫变.fac.svg");
//        File file1 = new File("C:\Users\33\Desktop\MXB.fac.svg");
        File file1 = new File("C:\Users\33\Desktop\220kVXJB.fac.svg");
        
        
        System.out.println("文件编码:" + new FileCharsetDetector().guessFileEncoding(file1));
    }

    /**
     * 传入一个文件(File)对象,检查文件编码
     * 
     * @param file
     *            File对象实例
     * @return 文件编码,若无,则返回null
     * @throws FileNotFoundException
     * @throws IOException
     */
    public String guessFileEncoding(File file) throws FileNotFoundException, IOException {
        return guessFileEncoding(file, new nsDetector());
    }

    /**
     * <pre>
     * 获取文件的编码
     * @param file
     *            File对象实例
     * @param languageHint
     *            语言提示区域代码 @see #nsPSMDetector ,取值如下:
     *             1 : Japanese
     *             2 : Chinese
     *             3 : Simplified Chinese
     *             4 : Traditional Chinese
     *             5 : Korean
     *             6 : Dont know(default)
     * </pre>
     * 
     * @return 文件编码,eg:UTF-8,GBK,GB2312形式(不确定的时候,返回可能的字符编码序列);若无,则返回null
     * @throws FileNotFoundException
     * @throws IOException
     */
    public String guessFileEncoding(File file, int languageHint) throws FileNotFoundException, IOException {
        return guessFileEncoding(file, new nsDetector(languageHint));
    }

    /**
     * 获取文件的编码
     * 
     * @param file
     * @param det
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    private String guessFileEncoding(File file, nsDetector det) throws FileNotFoundException, IOException {
        // Set an observer...
        // The Notify() will be called when a matching charset is found.
        det.Init(new nsICharsetDetectionObserver() {
            public void Notify(String charset) {
                encoding = charset;
                found = true;
            }
        });

        BufferedInputStream imp = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[1024];
        int len;
        boolean done = false;
        boolean isAscii = false;

        while ((len = imp.read(buf, 0, buf.length)) != -1) {
            // Check if the stream is only ascii.
            isAscii = det.isAscii(buf, len);
            if (isAscii) {
                break;
            }
            // DoIt if non-ascii and not done yet.
            done = det.DoIt(buf, len, false);
            if (done) {
                break;
            }
        }
        imp.close();
        det.DataEnd();

        if (isAscii) {
            encoding = "ASCII";
            found = true;
        }

        if (!found) {
            String[] prob = det.getProbableCharsets();
            //这里将可能的字符集组合起来返回
            for (int i = 0; i < prob.length; i++) {
                if (i == 0) {
                    encoding = prob[i];
                } else {
                    encoding += "," + prob[i];
                }
            }

            if (prob.length > 0) {
                // 在没有发现情况下,也可以只取第一个可能的编码,这里返回的是一个可能的序列
                return encoding;
            } else {
                return null;
            }
        }
        return encoding;
    }
}

 (3)、借助JCharDet获取文件字符集 - robin·张 - 博客园.html(https://www.cnblogs.com/amunote/p/4178472.html

      ZC:这个文章里面的代码,在检测 D:DRGISBINGraphics里面的图形时 能检测出 UTF-8编码的文件是UTF8编码

     ZC:看来 都是使用的 chardet.jar,编写的代码不一样 效果也是不同的。原始工具一样 使用者 水平很关键

  (3.1)、

package com.AAA;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;

/**
 * 借助JCharDet获取文件字符集
 * 
 * @author robin
 * 
 */
public class FileCharsetDetector01
{

    /**
     * 字符集名称
     */
    private static String encoding;
    
    /**
     * 字符集是否已检测到
     */
    private static boolean found;
    
    private static nsDetector detector;
    
    private static nsICharsetDetectionObserver observer;

    /**
     * 适应语言枚举
     * @author robin
     *
     */
    enum Language{
        Japanese(1),
        Chinese(2),
        SimplifiedChinese(3),
        TraditionalChinese(4), 
        Korean(5), 
        DontKnow(6);
        
        private int hint;
        
        Language(int hint){
            this.hint = hint;
        }
        
        public int getHint(){
            return this.hint;
        }
    }
    
    /**
     * 传入一个文件(File)对象,检查文件编码
     * 
     * @param file
     *            File对象实例
     * @return 文件编码,若无,则返回null
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String checkEncoding(File file) throws FileNotFoundException,
            IOException {
        return checkEncoding(file, getNsdetector());
    }

    /**
     * 获取文件的编码
     * 
     * @param file
     *            File对象实例
     * @param language
     *            语言
     * @return 文件编码
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String checkEncoding(File file, Language lang)
            throws FileNotFoundException, IOException {
        return checkEncoding(file, new nsDetector(lang.getHint()));
    }

    /**
     * 获取文件的编码
     * 
     * @param path
     *            文件路径
     * @return 文件编码,eg:UTF-8,GBK,GB2312形式,若无,则返回null
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String checkEncoding(String path) throws FileNotFoundException,
            IOException {
        return checkEncoding(new File(path));
    }

    /**
     * 获取文件的编码
     * 
     * @param path
     *            文件路径
     * @param language
     *                 语言
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String checkEncoding(String path, Language lang)
            throws FileNotFoundException, IOException {
        return checkEncoding(new File(path), lang);
    }

    /**
     * 获取文件的编码
     * 
     * @param file
     * @param det
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static String checkEncoding(File file, nsDetector detector)
            throws FileNotFoundException, IOException {
        
        detector.Init(getCharsetDetectionObserver());
        
        if (isAscii(file, detector)) {
            encoding = "ASCII";
            found = true;
        }

        if (!found) {
            String prob[] = detector.getProbableCharsets();
            if (prob.length > 0) {
                encoding = prob[0];
            } else {
                return null;
            }
        }
        
        return encoding;
    }
    
    /**
     * 检查文件编码类型是否是ASCII型
     * @param file
     *             要检查编码的文件
     * @param detector
     * @return
     * @throws IOException
     */
    private static boolean isAscii(File file, nsDetector detector) throws IOException{
        BufferedInputStream input = null;
        try{
            input = new BufferedInputStream(new FileInputStream(file));
            
            byte[] buffer = new byte[1024];
            int hasRead;
            boolean done = false;
            boolean isAscii = true;

            while ((hasRead=input.read(buffer)) != -1) {
                if (isAscii)
                    isAscii = detector.isAscii(buffer, hasRead);
                if (!isAscii && !done)
                    done = detector.DoIt(buffer, hasRead, false);
            }
            
            return isAscii;
        }finally{
            detector.DataEnd();
            if(null!=input)input.close();
        }
    }
    
    /**
     * nsDetector单例创建
     * @return
     */
    private static nsDetector getNsdetector(){
        if(null == detector){
            detector = new nsDetector();
        }
        return detector;
    }
    
    /**
     * nsICharsetDetectionObserver 单例创建
     * @return
     */
    private static nsICharsetDetectionObserver getCharsetDetectionObserver(){
        if(null==observer){
            observer = new nsICharsetDetectionObserver() {
                public void Notify(String charset) {
                    found = true;
                    encoding = charset;
                }
            };
        }
        return observer;
    }
    
    public static void main(String[] argv) throws Exception
    {
        //File file1 = new File("C:\Users\Administrator\Desktop\VideoViewDemo\VideoViewDemo\src\org\apache\android\media\AudioPlayer.java");
        //File file1 = new File("C:\Users\33\Desktop\zzz.g");
//        File file1 = new File("D:\DRGIS\BIN\Graphics\35kV娄宫变.fac.svg");
//        File file1 = new File("C:\Users\33\Desktop\MXB.fac.svg");
//        File file1 = new File("C:\Users\33\Desktop\220kVXJB.fac.svg");

        String str = FileCharsetDetector01.checkEncoding("C:\Users\33\Desktop\220kVXJB.fac.svg");
        System.out.println("文件编码:" + str);
    }
    
}

2、

3、

4、

5、

原文地址:https://www.cnblogs.com/javaskill/p/10015676.html