2012-07-16 27 views
1

我运行下面的代码的末端返回值:的Java InputStream.skip()附近的文件

public class SkipTest { 
    public static void main(String[] args) throws IOException { 
     FileOutputStream fileout = new FileOutputStream("./foo"); 
     DataOutputStream output = new DataOutputStream(fileout); 
     output.writeLong(12345678L); 
     output.writeLong(87654321L); 
     output.writeInt(1234); 
     output.flush(); 
     output.close(); 

     FileInputStream input = new FileInputStream("./foo"); 
     DataInputStream datain = new DataInputStream(input); 

     System.out.println(datain.readLong()); 
     System.out.println(datain.readLong()); 

     long skipped = datain.skip(8); 
     System.out.printf("Attempting to skip 8 bytes, actually skipped %d.\n", skipped); 

     datain.close(); 
    } 
} 

按照文档的.skip()返回值是字节的实际数目跳过,这可能小于要求的数量。我已经验证该文件是外部只有20个字节,但是当我运行上面的代码我得到以下输出:

12345678 
87654321 
Attempting to skip 8 bytes, actually skipped 8. 

所以这是一个错误还是我做错了什么?当文件中只剩4个字节时,它如何跳过8个字节?

回答

3

的DataInputStream类被向下通过的FileInputStream其要求其执行跳过以下:

“此方法可以跳过比在剩余的备份文件更多的字节这产生也不例外,跳过的字节数可能包含一些超出后备文件EOF的字节数,在跳过结尾后尝试从流中读取,将导致-1指示文件结束。

+0

谢谢,我只是看着InputStream的文档,我没想到要检查FileInputStream。我仍然认为它的误导性表示返回值是“实际跳过的字节数”。 – job 2012-07-16 21:32:19

1

您可以跳过FileInputStream中的任意字节数,显然没有读取任何内容。它只会重新定位光标,然后下一次读取会失败。尝试datain.skip(Integer.MAX_VALUE)