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).
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.
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 .
The read() method of a FileInputStream returns an int which contains the byte value of the byte read.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With