当前位置: 首页 > 工具软件 > cpdetector > 使用案例 >

使用第三方库获得一个文件的编码格式--cpdetector

施阳夏
2023-12-01

先把这个工具分享出来

链接:https://pan.baidu.com/s/1JNg6cJspxa5hL0xMChsclg 
提取码:34v1 

最近在维护的多媒体app有一个bug,就是播放视屏时,如果视屏带的外挂srt字幕,则解析字幕并显示后,字幕乱码。最后发现是因为有的srt字幕的编码不同,因为系统默认是使用的UTF-8编码,所以,这就需要在设置外挂字幕前,先读出srt文件的编码格式,然后在提示显示字幕的时候,将这个编码设置下去。于是乎,问题难点就变成了如何去识别srt文件编码的格式。

经过查找,发现有一个cpdetector的库可以很好的识别(但是不保证完全准确)

如下:

public static String getFileEncode(String filePath) {
        String charsetName = null;
        try {
            File file = new File(filePath);
            CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
            detector.add(new ParsingDetector(false));
            detector.add(JChardetFacade.getInstance());
            detector.add(ASCIIDetector.getInstance());
            detector.add(UnicodeDetector.getInstance());
            java.nio.charset.Charset charset = null;
            charset = detector.detectCodepage(file.toURI().toURL());
            if (charset != null) {
                charsetName = charset.name();
            } else {
                charsetName = "UTF-8";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return charsetName;
    }
 类似资料: