Does FileInputStream.skip() do a seek?

2019-04-19 12:35发布

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

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-19 12:45

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.

查看更多
smile是对你的礼貌
3楼-- · 2019-04-19 12:48

you will be interested with this LINK

it say that seek is faster than skip

查看更多
登录 后发表回答