将具有已知编码的文件转换为UTF-8

时间:2010-12-08 01:51:43

标签: java eclipse unicode encoding utf-8

我需要将文本文件转换为String,最后,我应该将其作为输入参数(类型为InputStream)放到IFile.create(Eclipse)中。 寻找示例或如何做但仍然无法弄清楚...需要你的帮助!

仅用于测试,我尝试将原始文本文件转换为使用此代码编码的UTF-8

FileInputStream fis = new FileInputStream(FilePath);
InputStreamReader isr = new InputStreamReader(fis);

Reader in = new BufferedReader(isr);
StringBuffer buffer = new StringBuffer();

int ch;
while ((ch = in.read()) > -1) {
    buffer.append((char)ch);
}
in.close();


FileOutputStream fos = new FileOutputStream(FilePath+".test.txt");
Writer out = new OutputStreamWriter(fos, "UTF8");
out.write(buffer.toString());
out.close();

但是即使最终的* .test.txt文件有UTF-8编码,里面的字符也会被破坏。

1 个答案:

答案 0 :(得分:9)

您需要使用InputStreamReader参数指定Charset的编码。

                                    // ↓ whatever the input's encoding is
Charset inputCharset = Charset.forName("ISO-8859-1");
InputStreamReader isr = new InputStreamReader(fis, inputCharset));

这也有效:

InputStreamReader isr = new InputStreamReader(fis, "ISO-8859-1"));

另见:

搜索我找到所有这些链接的地方:https://stackoverflow.com/search?q=java+detect+encoding


您可以在运行时通过Charset.defaultCharset()获取默认字符集 - 它来自运行JVM的系统。