2011-09-03 70 views
0

我需要读取包括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. 请帮助我。例如:.txt包含文本的文件。

a 
b 
c 

readInt();仅仅只读取ab

+0

也许我misundertood你,但没有“档案结尾”字被阅读。 –

+1

请解释一下:_So如果文本文件只包含一行文本,总和为0._ –

+0

我不确定你想实现什么,但我认为_DataInputStream_是错误的选择。你想逐行阅读一个数字列表吗? – home

回答

3

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

我们来分析一下您的示例文件:

a 
b 
c 

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

readInt()方法采用四个第一个字节并将其作为int。这意味着当您尝试再次调用它时,只剩下一个字节,这是不够的。

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


为了证明,这是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)); 
    } 

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

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