Java InputStream.skip()在文件末尾附近返回值 [英] Java InputStream.skip() return value near end of file

查看:864
本文介绍了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."

这篇关于Java InputStream.skip()在文件末尾附近返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆