我正在运行以下代码:
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 个字节?
最佳答案
DataInputStream 正在通过 FileInputStream 向下传递,FileInputStream 声明以下内容用于其 skip 的实现:
“此方法跳过的字节数可能多于备份文件中剩余的字节数。这不会产生异常,并且跳过的字节数可能包括一些超出备份文件 EOF 的字节数。正在尝试从流中读取跳过结尾后将导致 -1 表示文件结尾。”
关于Java InputStream.skip() 返回值接近文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11511093/