工作笔记之—文件编码转换

来源:互联网 发布:电视万能遥控器软件 编辑:程序博客网 时间:2024/05/06 20:45

今天老大给了我一个任务,我之前写的文件管理系统中有一个读txt文件的功能。但是这个只支持utf-8的编码格式。新的需求是让它支持更多的编码格式,不然读出来可就是乱码喽。

下面说一下具体的解决方法。


1.判断txt文件的编码格式

  相信很多人知道,txt文件的编码格式一共有四种,分别是“GBK”,“UTF-8”,“Unicode”,‘“UTF-16BE”。这些编码格式的区别在于写入头文件的信息不同,为了在读文件的时候不出现乱码,我们需要判断出你所要读的文件的编码类型,然后以这种类型来读文件。

第一步,判断文件的编码类型:

public String codeString(File file) {
        BufferedInputStream bin;
        int p = 0;
        try {
            bin = new BufferedInputStream(new FileInputStream(file));
            p = (bin.read() << 8) + bin.read();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String code = null;

        switch (p) {
        case 0xefbb:
            code = "UTF-8";
            break;
        case 0xfffe:
            code = "Unicode";
            break;
        case 0xfeff:
            code = "UTF-16BE";
            break;
        default:
            code = "GBK";
        }

        return code;
    }



2.以文件自己的编码类型读文件本身

将上面方法的返回值作为参数传进读文件这个方法。

    public String readTxtFile(File file, String code) {
        StringBuffer txtFile = new StringBuffer();
        try {
            InputStream inputStream = new FileInputStream(file);
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream, code);
                BufferedReader buffreader = new BufferedReader(
                        inputStreamReader);
                String line;
                // 分行读取
                while ((line = buffreader.readLine()) != null) {
                    txtFile.append(line + "\n");
                }
                inputStream.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return txtFile.toString();
    }

0 0
原创粉丝点击