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

标签 java eclipse unicode encoding utf-8

我需要将文本文件转换为字符串,最后,我应该将其作为输入参数(类型 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 编码,里面的字符也已损坏。

最佳答案

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

                                    // ↓ 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"));

另见:

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


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

关于java - 将已知编码的文件转换为 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383504/

相关文章:

Java Hamcrest : Collection contains item of type

java - 按日期和时间对 ArrayList 的对象进行排序

java - Eclipse 电子邮件 + 图片

java - 如何使用 android.graphics 绘制图像?

php - 隐藏字符(看起来像子弹)破坏文件

php - 如何用PHP解析特殊字符到MySQL?

Java、Alfresco Web 服务 API 和 Unicode NamedValues

java - 创建所有可能的诗歌排列

java - 在java中使用PDFBox围绕其中心旋转PDF

eclipse - java.lang.NoClassDefFoundError : org/springframework/context/ApplicationContext