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个字节,但是当我运行上面的代码时,我得到以下输出:
According to the docs, the return value of .skip()
is the actual number of bytes skipped, which may be less than the requested number. I've verified that the file is only 20 bytes externally, but when I run the code above I get the following output:
12345678
87654321
Attempting to skip 8 bytes, actually skipped 8.
所以这是一个错误还是我做错了什么?当文件中只剩4个时,如何跳过8个字节?
So is this a bug or am I doing something wrong? How can it skip 8 bytes when there are only 4 left in the file?
DataInputStream向下传递FileInputStream声明以下是跳过的实现:
The DataInputStream is passing down through FileInputStream which claims the following for its implementation of skip:
此方法可能会跳过比备份文件中剩余的更多的字节。这不会产生异常,跳过的字节数可能包括超出后备文件EOF的一些字节数。跳过结束后尝试从流中读取将导致-1表示文件结束。
"This method may skip more bytes than are remaining in the backing file. This produces no exception and the number of bytes skipped may include some number of bytes that were beyond the EOF of the backing file. Attempting to read from the stream after skipping past the end will result in -1 indicating the end of the file."