美文网首页
文本编码格式自动识别

文本编码格式自动识别

作者: Weller0 | 来源:发表于2018-09-14 15:42 被阅读0次
public void parse(String uri) {
        File subtitlesFile = new File(uri);
        String line;
        FileInputStream is;
        BufferedReader in;
        try {
            is = new FileInputStream(subtitlesFile);
            in = getBufferedReader(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }
        if (in != null) {
            try {
                while ((line = in.readLine()) != null) {
                    ... ...
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            L.e(TAG, "readLine : read subtitle file fail.");
        }
    }

/**
 * 根据文本的前三个字节决定编码格式
**/
private BufferedReader getBufferedReader(FileInputStream fis) {
        BufferedReader reader = null;
        BufferedInputStream in = new BufferedInputStream(fis);
        in.mark(4);
        byte[] first3bytes = new byte[3];
        try {
            in.read(first3bytes);//找到文档的前三个字节并自动判断文档类型
            in.reset();
            if (first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB && first3bytes[2] == (byte) 0xBF) {
                reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
            } else if (first3bytes[0] == (byte) 0xFF && first3bytes[1] == (byte) 0xFE) {
                reader = new BufferedReader(new InputStreamReader(in, "unicode"));
            } else if (first3bytes[0] == (byte) 0xFE && first3bytes[1] == (byte) 0xFF) {
                reader = new BufferedReader(new InputStreamReader(in, "utf-16be"));
            } else if (first3bytes[0] == (byte) 0xFF && first3bytes[1] == (byte) 0xFF) {
                reader = new BufferedReader(new InputStreamReader(in, "utf-16le"));
            } else {
                reader = new BufferedReader(new InputStreamReader(in, "GBK"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reader;
    }

相关文章

  • 文本编码格式自动识别

  • Vim 常用功能

    文件查看 文本格式查看 编码格式 fileencodings fileencoding encoding term...

  • 文本文件的编码格式是怎么判断的?

    不同编码的文本,是根据文本的前两个字节来定义其编码格式的。定义如下:ANSI: 无格式定义;Unicode: 前两...

  • [ 编码 ] BASE64编码-小图片不通过流方式上传可以吗?

    Base64编码 Base64编码是对二进制数据进行编码,表示成文本格式图片上传可以分为流上传跟文本上传这里的文本...

  • java学习笔记#4-File

    编码浅析 编码格式实例 文本文件就是字符序列,它可以是任意编码,中文机器上创建文本文件时,默认ansi编码。不同的...

  • 文本文件的编码格式

    文本文件的编码格式,都在3A服务器上进行测试 一、文本文件 文本文件存储的内容是基于 字符编码 的文件,常见的编码...

  • 代码判断文本编码格式

    前几天项目中有这样的需求:客户端需要在服务器下载一个文本文件显示出来。bug是mac上的中文显示乱码。通过查找看项...

  • Asp.net MVC ActionResult返回值

    1 视图类型 返回视图 2 文本类型 可以指定返回的文本内容,编码格式和文本类型(MIME类型) 返回JavaSc...

  • C_language_renew09

    文件 文件分两类:文本文件、二进制文件 文本文件:是基于字符编码的文件常见的编码有ASCII。以ASCII格式存放...

  • 数据清洗|JSON格式

    日拱一卒|数据挖掘004 格式、类型与编码(二) 一、文件格式 2.常见的文本文件格式 (2)JSON格式 JSO...

网友评论

      本文标题:文本编码格式自动识别

      本文链接:https://www.haomeiwen.com/subject/fevogftx.html