javafilestreams

Java open stream from an arbitrary location in file


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?


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