如何读取二进制文件直到文件结束?

时间:2011-09-03 13:44:57

标签: java binaryfiles eof

我需要读取包含eof的二进制文件。

我使用DataInputStream

读取文件
DataInputStream instr = new DataInputStream(new BufferedInputStream(new FileInputStream( fileName ) ) );

我使用readInt();将二进制文件读取为整数。

try {
    while ( true){
        System.out.println(instr.readInt());
        sum += instr.readInt(); //sum is integer
    }
} catch ( EOFException  eof ) {
    System.out.println( "The sum is: " + sum );
    instr.close();
}

但是这个程序不会读取文件结尾或最后一行文本(如果是文本文件)。 因此,如果文本文件仅包含一行文本,则总和为0。 请帮帮我。

示例:if .txt文件包含文本。

a
b
c

readInt();只能阅读ab

2 个答案:

答案 0 :(得分:3)

这确实很正常。您正在尝试读取字节,而不是整数。 readInt()方法将四个字节一起融合为一个int。

让我们分析您的示例文件:

a
b
c

这完全是5个字节:a\nb\nc
\n是换行符。

readInt()方法获取前四个字节并生成一个int。这意味着当你尝试再次调用它时,只剩下一个字节,这还不够。

尝试使用readByte()代替,它将逐个返回所有字节。


要演示,这是readInt()方法的主体,它会将read()调整4次:

   public final int readInt() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        int ch3 = in.read();
        int ch4 = in.read();
        if ((ch1 | ch2 | ch3 | ch4) < 0)
            throw new EOFException();
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }

当到达文件末尾时,-1方法返回read()。这就是检测EOFExceptions的方式。

答案 1 :(得分:0)

在你的情况下,最好使用一个Reader并使用.next()和.nextLine()

FileReader reader = new FileReader(fileName);
Scanner scanner = new Scanner(reader );
String sum;
while (scanner.hasNext()) {
  sum += scanner.next()) {
}
reader.close();
System.out.println( "The sum is: " + sum );
相关问题