gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:38:31 25 4
gpt4 key购买 nike

我需要将文本文件转换为字符串,最后,我应该将其作为输入参数(类型 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com