java文件阅读问题

时间:2011-12-15 05:42:48

标签: java file-io

在我的java应用程序中,我必须读取一个文件。我所面临的问题是,在阅读文件后,结果将以不可读的格式出现。这意味着会显示一些ascii字符。这意味着所有字母都不可读。如何让它显示出来?

 // Open the file that is the first
        // command line parameter

        FileInputStream fstream = new FileInputStream("c:\\hello.txt");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console
            System.out.println(strLine);
        }
        // Close the input stream
        in.close();
    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

5 个答案:

答案 0 :(得分:1)

也许您有编码错误。您用于InputStreamReader的构造函数使用默认字符编码;如果您的文件包含ASCII范围之外的UTF-8文本,您将获得垃圾。此外,您不需要DataInputStream,因为您没有从流中读取任何数据对象。试试这段代码:

FileInputStream fstream = null;
try {
    fstream = new FileInputStream("c:\\hello.txt");
    // Decode data using UTF-8
    BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    String strLine;
    // Read File Line By Line
    while ((strLine = br.readLine()) != null) {
        // Print the content on the console
        System.out.println(strLine);
    }
} catch (Exception e) {// Catch exception if any
    System.err.println("Error: " + e.getMessage());
} finally {
    if (fstream != null) {
        try { fstream.close(); }
        catch (IOException e) {
            // log failure to close file
        }
    }
}

答案 1 :(得分:0)

你必须以这种方式来处理: -

BufferedReader br = new BufferedReader(new InputStreamReader(in, encodingformat));

encodingformat - 根据您遇到的编码问题类型进行更改。

示例: UTF-8 UTF-16 ,......很快

有关详情,请参阅 Supported Encodings by Java SE 6

答案 2 :(得分:0)

由于您不知道文件所在的编码,因此请使用jchardet检测文件使用的编码,然后使用该编码读取其他人已建议的文件。这不是100%万无一失,但适用于您的场景。

此外,不需要使用DataInputStream

答案 3 :(得分:0)

您获得的输出是ascii值,因此您需要在打印之前键入将其转换为char或string。希望这有帮助

答案 4 :(得分:0)

我的问题解决了。我不知道怎么做。我将hello.txt内容复制到另一个文件并运行java程序。我可以阅读所有的信件。不知道那是什么问题。

相关问题