java FileInputStream.skip() 是否进行搜索?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3669598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:56:23  来源:igfitidea点击:

Does FileInputStream.skip() do a seek?

javainputstreamseekrandom-access

提问by Mike Q

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?

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

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).

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

回答by The Alchemist

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

取决于您的 JVM,但这里FileInputStream.skip()是最近的 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 RandomAccessFileis non-standard. It's part of the java.iopackage and has been since 1.0.

看起来它正在做一个seek(). 但是,我不明白为什么RandomAccessFile是非标准的。它是java.io软件包的一部分,自 1.0 以来一直存在。

回答by Bilel Boulifa

you will be interested with this LINK

你会对这个LINK感兴趣

it say that seek is faster than skip

它说寻找比跳过快