读取文本文件时显示的文本不正确

时间:2014-09-11 04:16:35

标签: java text-files

我正在编写一个程序来读取文本文件。当我打印读取值时,值显示不正确。 文本文件包含以下数据

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();
            }
        }

    }
}

输出如下:

enter image description here

请帮助解决此问题。为什么我将输出显示为乱码。

2 个答案:

答案 0 :(得分:1)

这是一个编码问题,从输出中看起来该文件是以某种UTF-16变体编码的。由于FileReader始终使用平台的默认编码,因此请尝试:

new BufferedReader(
    new InputStreamReader(
        new FileInputStream("C:\\IASTATE\\test.txt"), "UTF-16LE"));

答案 1 :(得分:0)

这可能不是您遇到问题的原因,但使用FileReader通常是一个坏主意,因为始终使用当前平台的默认编码。因此,如果您的文件是使用不同的编码创建的,它可能会打印出“垃圾”。您可以尝试改为:

BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\IASTATE\\test.txt"), StandardCharsets.UTF_8));

使用StandardCharsets.UTF_8文件的编码替换test.txt