FileInputStream.skip() 是否进行查找?

发布于 2024-09-18 01:54:32 字数 242 浏览 6 评论 0原文

我想将一个可能很大的文件的最后 10MB 复制到另一个文件中。理想情况下,我会使用 FileInputStream、skip(),然后 read()。但是我不确定skip()的性能是否会很差。 Skip() 通常是使用下面的文件查找来实现的,还是实际上读取并丢弃数据?

我知道 RandomAccessFile 但我感兴趣的是我是否可以使用 FileInputStream 来代替它(RandomAccessFile 很烦人,因为 API 是非标准的)。

I want to copy the last 10MB of a possibly large file into another file. Ideally I would use FileInputStream, skip() and then read(). However I'm unsure if the performance of skip() will be bad. Is skip() typically implemented using a file seek underneath or does it actually read and discard data?

I know about RandomAccessFile but I'm interested in whether I could use FileInputStream in place of that (RandomAccessFile is annoying as the API is non-standard).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼睛会笑 2024-09-25 01:54:38

你会对这个 LINK 感兴趣,

它说要寻求比跳过更快

you will be interested with this LINK

it say that seek is faster than skip

书间行客 2024-09-25 01:54:37

取决于您的 JVM,但这是最近 openjdk 的 FileInputStream.skip() 的源代码:

JNIEXPORT jlong JNICALL
Java_java_io_FileInputStream_skip(JNIEnv *env, jobject this, jlong toSkip) {
    jlong cur = jlong_zero;
    jlong end = jlong_zero;
    FD fd = GET_FD(this, fis_fd);
    if (fd == -1) {
        JNU_ThrowIOException (env, "Stream Closed");
        return 0;
    }
    if ((cur = IO_Lseek(fd, (jlong)0, (jint)SEEK_CUR)) == -1) {
        JNU_ThrowIOExceptionWithLastError(env, "Seek error");
    } else if ((end = IO_Lseek(fd, toSkip, (jint)SEEK_CUR)) == -1) {
        JNU_ThrowIOExceptionWithLastError(env, "Seek error");
    }
    return (end - cur);
}

看起来它正在执行 seek()。但是,我不明白为什么 RandomAccessFile 是非标准的。它是 java.io 包的一部分,从 1.0 开始就存在。

Depends on your JVM, but here's the source for FileInputStream.skip() for a recent openjdk:

JNIEXPORT jlong JNICALL
Java_java_io_FileInputStream_skip(JNIEnv *env, jobject this, jlong toSkip) {
    jlong cur = jlong_zero;
    jlong end = jlong_zero;
    FD fd = GET_FD(this, fis_fd);
    if (fd == -1) {
        JNU_ThrowIOException (env, "Stream Closed");
        return 0;
    }
    if ((cur = IO_Lseek(fd, (jlong)0, (jint)SEEK_CUR)) == -1) {
        JNU_ThrowIOExceptionWithLastError(env, "Seek error");
    } else if ((end = IO_Lseek(fd, toSkip, (jint)SEEK_CUR)) == -1) {
        JNU_ThrowIOExceptionWithLastError(env, "Seek error");
    }
    return (end - cur);
}

Looks like it's doing a seek(). However, I don't see why RandomAccessFile is non-standard. It's part of the java.io package and has been since 1.0.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文