Search code examples
javafileinputstream

Skipping backward in a file in java


I'm using FileInputStream in Java to parse an input file, and I want to be able to skip backwards within that file. I have had mixed results, and according to the Javadocs this is not possible, though it has worked in other parts of the program. Currently I am getting an:

'Exception in thread "main" java.io.IOException: Invalid argument'

I believe RandomAccessFile yields the same problem. Any tips that would make this possible?

EDIT:
An example of where the error is occurring:

FileInputStream file = new FileInputStream(inputfile);
file.read(check,0,6);
file.skip(-6);

Solution

  • If you get the FileChannel associated with the FileInputStream you can set the position on the channel, which will affect the next read from the stream.

    Similarly, if you use a RandomAccessFile, you can seek to a desired position in file.