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
Does FileInputStream.skip() do a seek?
提问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 RandomAccessFile
is non-standard. It's part of the java.io
package and has been since 1.0.
看起来它正在做一个seek()
. 但是,我不明白为什么RandomAccessFile
是非标准的。它是java.io
软件包的一部分,自 1.0 以来一直存在。