我需要将文本文件转换为字符串,最后,我应该将其作为输入参数(类型 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"));
另见:
-
InputStreamReader(InputStream in, Charset cs)
-
Charset.forName(String charsetName)
- Java: How to determine the correct charset encoding of a stream
- How to reliably guess the encoding between MacRoman, CP1252, Latin1, UTF-8, and ASCII
- GuessEncoding - 仅适用于 UTF-8、UTF-16LE、UTF-16BE 和 UTF-32 ☹
- ICU Charset Detector
- cpdetector , 免费java代码页检测
- JCharDet (Mozilla 字符集检测器的 Java 端口)具有讽刺意味的是,该页面没有正确呈现“Mozilla's”中的撇号
SO 搜索我找到所有这些链接的位置:https://stackoverflow.com/search?q=java+detect+encoding
您可以在运行时通过 Charset.defaultCharset()
获取默认字符集 - 它来自运行 JVM 的系统。
关于java - 将已知编码的文件转换为 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383504/