Question

I want to get a Stream from some arbitrary position in an existing file, for example I need to read/write from/to a file starting with 101th byte. Is it safe to use something like that?

final FileInputStream fin = new FileInputStream(f);
fin.skip(100);

Skip javadoc tells that it may sometimes skip lesser number of bytes than specified. What should I do then?

Was it helpful?

Solution

How about the following:

final RandomAccessFile raf = new RandomAccessFile(f, mode);
raf.seek(100);
final FileInputStream fin = new FileInputStream(raf.getFD());
// read from fin

OTHER TIPS

you can't write using a FileInputStream. you need to use a RandomAccessFile if you want to write to arbitrary locations in a file. eunfortunately, there is no easy way to use a RandomAccessFile as an InputStream/OutputStream (looks like @aix may have a good suggestion for adapting RandomAccessFile to InputStream/OutputStream), but there are various example adapters available online.

another alternative is to use a FileChannel. you can set the position of the FileChannel directly, then use the Channels utility methods to get InputStream/OutputStream adapters on top of the Channel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top