Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does FileInputStream.skip() do a seek?

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

like image 334
Mike Q Avatar asked Sep 08 '10 15:09

Mike Q


People also ask

Which exception is thrown by FileInputStream?

The FileInputStream read() method throws a java. io. IOException if for some reason it can't read from the file. Again, the InputFile class makes no attempt to catch or declare this exception.

How does FileInputStream work in Java?

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .

What does the read () method of FileInputStream return?

The read() method of a FileInputStream returns an int which contains the byte value of the byte read.

What is the difference between FileInputStream and InputStream?

There is no real difference. FileInputStream extends InputStream , and so you can assign an InputStream object to be a FileInputStream object. In the end, it's the same object, so the same operations will happen. This behavior is called Polymorphism and is very important in Object-Oriented Programming.


1 Answers

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.

like image 50
The Alchemist Avatar answered Sep 19 '22 06:09

The Alchemist