BufferedWriter 在保存到新文件时输出奇怪的字符

BufferedWriter outputting strange characters when saved to new file

我正在使用以下代码逐行处理一个大文本文件。问题是我使用的是英语以外的语言,准确地说是克罗地亚语。许多字符在输出文件中显示为 �。我该如何解决?

该文件是 ANSI 格式,但这似乎不是与 InputStreamReader 兼容的编码类型。我应该将原始文件保存为哪种编码类型?

try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {

 String line;
 try {
  try (
   InputStream fis = new FileInputStream("C:\Users\marti\Documents\Software Projects\Java Projects\TwitterAutoBot\src\main\resources\EH.Txt"); InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr);
  ) {
   while ((line = br.readLine()) != null) {
    // Deal with the line

    String content = line.substring(line.lastIndexOf("  ") + 1);
    System.out.println(content);

    bw.write("\n\n" + content);

   }
  }
 } catch (IOException e) {
  e.printStackTrace();
 }

 // bw.close();

} catch (IOException e) {

 e.printStackTrace();

}

您需要使用InputStreamReader/OutputStreamWriter constructors that take a Charset。您正在使用的构造函数正在使用您平台的默认字符集,这显然不是您需要的。

如果您使用的是 Java 8 或更高版本,您可以使用 Files 中的一种便捷方法:

您需要确保使用正确的字符集读取输入文件,并以支持您尝试写入的字符的字符集写入文件。 UTF-8 是一种合适的输出文件格式。

我用 Cp1252 而不是 UTF-8 编码解决了这个问题,因为文件是用 ANSI.

编码的