简体   繁体   English

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

[英]How to read binary file until the end-of-file?

I need to read binary file including the eof . 我需要读取包括eof二进制文件。

I read file using DataInputStream 我使用DataInputStream读取文件

DataInputStream instr = new DataInputStream(new BufferedInputStream(new FileInputStream( fileName ) ) );

And I used readInt(); 我使用了readInt(); to read binary file as an integer. 将二进制文件读取为整数。

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

But this program doesn't read the End-of-file or last line of text(if it's text file). 但是此程序不会读取文件的末尾或文本的最后一行(如果是文本文件)。 So if the text file is only contained only one line of text, the sum is 0. Please help me with this. 因此,如果文本文件仅包含一行文本,则总和为0。请帮助我。

Example: if .txt file containing the text. 示例:如果.txt文件包含文本。

a
b
c

readInt(); just only reads a and b . 仅读取ab

That's indeed normal. 确实很正常。 You are trying to read the bytes, and not ints. 您正在尝试读取字节,而不是整数。 The readInt() method melts four bytes together to an int. readInt()方法将四个字节readInt()

Let's analyse your example file: 让我们分析一下示例文件:

a
b
c

This is totally 5 bytes: a , \\n , b , \\n , c . 这总共是5个字节: a\\nb\\nc
\\n are newlines. \\n是换行符。

The readInt() method takes the four first bytes and makes an int of it. readInt()方法获取前四个字节并对其进行int处理。 This means when you try to make a second call to it, there is only one byte left, which is not enough. 这意味着当您尝试对其进行第二次调用时,仅剩一个字节,这是不够的。

Try to use readByte() instead, which will return all the bytes, one by one. 尝试改用readByte() ,它将一一返回所有字节。


To demonstrate, this is the body of the readInt() method, it calles 4 times read() : 为了演示,这是readInt()方法的主体,它调用了4次read()

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

When the end of a file is reached, -1 is returned from the read() method. 到达文件末尾时,从read()方法返回-1 That is how EOFExceptions are detected. 这就是检测EOFException的方式。

In your case it might be better to use a Reader and use .next() and .nextLine() 在您的情况下,最好使用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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM