我正在编写一个程序来读取文本文件。当我打印读取的值时,这些值显示不正确。 文本文件包含以下数据
This is line one
This is line two
This is line three
This is line four
读取文本文件的代码如下:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SearchFile {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
输出如下:
请帮助解决此问题。为什么我的输出显示为垃圾字符。
最佳答案
这是一个编码问题,从输出来看,该文件似乎是以某种 UTF-16 变体编码的。由于 FileReader
始终使用平台的默认编码,因此请尝试一下:
new BufferedReader(
new InputStreamReader(
new FileInputStream("C:\\IASTATE\\test.txt"), "UTF-16LE"));
关于java - 读取文本文件时显示的文本不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25778994/