【发布时间】:2018-05-31 08:17:26
【问题描述】:
我正在使用以下代码逐行处理一个大文本文件。问题是我使用的是英语以外的语言,准确地说是克罗地亚语。许多字符在输出文件中显示为 �。我该如何解决这个问题?
该文件采用 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();
}
【问题讨论】:
-
您的输入文件使用什么编码?
-
@GregKopff 它在 ANSI 中。
-
@MartinErlic 如果是
ANSI,为什么你在代码中指定了UTF-8? --- 如果是ANSI,那是extended ANSI的哪个味道? -
因为我没有事先检查文件的字符编码!
-
但是,ANSI 不是 InputStreamReader 中可识别的编码类型。有人建议使用
US-ASCII,但这也不起作用,会产生同样奇怪的字符。也没有将文件保存为 UTF-8,因为我丢失了翻译。
标签: java inputstream filewriter bufferedwriter