1

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?

frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115
Vic
  • 21,473
  • 11
  • 76
  • 97

2 Answers2

3

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.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • Thanks for pointing me into the direction of RandomAccessFile. Eventually RandomAccessFile was all I needed, but @aix has given the exact answer I've been looking for. – Vic Oct 19 '11 at 09:08
1

How about the following:

final RandomAccessFile raf = new RandomAccessFile(f, mode);
raf.seek(100);
final FileInputStream fin = new FileInputStream(raf.getFD());
// read from fin
NPE
  • 486,780
  • 108
  • 951
  • 1,012