【问题标题】:Convert File with known encoding to UTF-8将已知编码的文件转换为 UTF-8
【发布时间】:2011-05-21 23:24:38
【问题描述】:

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

【问题讨论】:

  • 顺便说一句,你在写一个 Eclipse 插件吗?你为什么用IFile
  • 是的,这是在 Eclipse 插件中!

标签: java eclipse unicode encoding utf-8


【解决方案1】:

您需要使用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"));

另见:

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


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

【讨论】:

  • 谢谢回复,但是我是从isr获取Encoding(isr.getEncoding()),不是已经知道encoding是什么了吗?
  • 我这样做对吗: InputStreamReader isr1 = new InputStreamReader(fis);字符集 inputCharset = Charset.forName(isr1.getEncoding()); InputStreamReader isr = new InputStreamReader(fis, inputCharset)); ?
  • @Jack:不,这不是它的工作方式。真的没有办法知道任意文本块的编码。如果您没有指定InputStreamReader 的编码,那么阅读器将拥有(因此isr.getEncoding() 将返回)默认 编码。
  • @Jack:嘿,我以为你说文件的编码是已知的。是什么赋予了? :P
  • joelonsoftware.com/articles/Unicode.html,推荐阅读,首先给自己看!
猜你喜欢
  • 2012-01-15
  • 1970-01-01
  • 2020-10-11
  • 2013-09-12
  • 1970-01-01
  • 2012-06-30
  • 2020-07-28
  • 2011-06-26
  • 2014-02-02
相关资源
最近更新 更多