Java RandomAccessFileInputStream-class And Method Code Example


Here is an example of how you might use the RandomAccessFileInputStream class from the org.apache.commons.io package in Java:

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.input.RandomAccessFileInputStream;

public class MyClass {

    public void doSomethingWithRandomAccessFileInputStream() throws IOException {
        // Create a File object
        File file = new File("example.txt");

        // Open a random access file input stream
        RandomAccessFileInputStream rafis = new RandomAccessFileInputStream(file);

        // Seek to a specific position in the file
        rafis.seek(5);

        // Read data from the file
        int value = rafis.read();
        while (value != -1) {
            System.out.println(value);
            value = rafis.read();
        }
    }
}

The RandomAccessFileInputStream class is a subclass of InputStream that allows random access to a file. It uses a RandomAccessFile object to access the file, so it provides similar functionality. In this example, we opened a random access file input stream on a file called "example.txt" and seek to position 5, read the data from that position.

The RandomAccessFileInputStream class also provides a seek(long pos) method to change the current position in the file and a getFilePointer() method to get the current position in the file.

Note that it is important to close the RandomAccessFileInputStream after you are done with it to release the resources associated with the file.