将具有已知编码的文件转换为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编码,里面的字符也会被破坏。

您需要使用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:如何确定流的正确charset编码
  • 如何可靠地猜测MacRoman,CP1252,Latin1,UTF-8和ASCII之间的编码
  • GuessEncoding – 仅适用于UTF-8,UTF-16LE,UTF-16BE和UTF-32☹
  • ICU Charset探测器
  • cpdetector ,免费java代码页检测
  • JCharDet (Mozilla charset探测器的Java端口) 具有讽刺意味的是,该页面无法正确呈现“Mozilla”中的撇号

搜索我发现所有这些链接: https : //stackoverflow.com/search?q = java + detect +encoding


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