Java InputStream.skip()返回文件末尾附近的值
我正在运行以下代码:Java InputStream.skip()返回文件末尾附近的值,java,inputstream,Java,Inputstream,我正在运行以下代码: public class SkipTest { public static void main(String[] args) throws IOException { FileOutputStream fileout = new FileOutputStream("./foo"); DataOutputStream output = new DataOutputStream( fileout ); output.wri
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.
这是一个bug还是我做错了什么?当文件中只剩下4个字节时,它怎么能跳过8个字节呢?您可以跳过
文件输入流中任意数量的字节,显然不需要读取任何内容。它将重新定位光标,然后下一次读取将失败。尝试datain.skip(Integer.MAX_VALUE)
您可以跳过文件输入流中任意数量的字节,显然不需要读取任何内容。它将重新定位光标,然后下一次读取将失败。请尝试datain.skip(Integer.MAX_VALUE)
DataInputStream正在通过FileInputStream向下传递,FileInputStream声明了其skip的以下实现:
“此方法跳过的字节数可能超过备份文件中剩余的字节数。这不会产生任何异常,跳过的字节数可能包括超出备份文件EOF的某些字节数。跳过结束后尝试从流中读取将导致-1表示文件结束。”DataInputStream通过FileInputStream向下传递,FileInputStream为其skip的实现声明了以下内容:
“此方法跳过的字节数可能超过备份文件中剩余的字节数。这不会产生异常,跳过的字节数可能包括超出备份文件EOF的某些字节数。跳过结束后尝试从流中读取将导致-1表示文件结束。”谢谢,我只是在查看文档中的InputStream,没有想到要检查FileInputStream。我仍然认为它说返回值是“跳过的实际字节数”是误导性的。谢谢,我只是查看了InputStream的文档,我没有想到检查FileInputStream。我仍然认为它说返回值是“实际跳过的字节数”是误导。