How to read a file from a certain offset in Java?

前端 未结 2 1881
难免孤独
难免孤独 2020-11-27 20:27

Hey I\'m trying to open a file and read just from an offset for a certain length! I read this topic: How to read a specific line using the specific line number from a file

相关标签:
2条回答
  • 2020-11-27 20:34

    FileInputStream.getChannel().position(123)

    This is another possibility in addition to RandomAccessFile:

    File f = File.createTempFile("aaa", null);
    byte[] out = new byte[]{0, 1, 2};
    
    FileOutputStream o = new FileOutputStream(f);
    o.write(out);
    o.close();
    
    FileInputStream i = new FileInputStream(f);
    i.getChannel().position(1);
    assert i.read() == out[1];
    i.close();
    f.delete();
    

    This should be OK since the docs for FileInputStream#getChannel say that:

    Changing the channel's position, either explicitly or by reading, will change this stream's file position.

    I don't know how this method compares to RandomAccessFile however.

    0 讨论(0)
  • 2020-11-27 20:57

    RandomAccessFile exposes a function:

    seek(long pos) 
              Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
    
    0 讨论(0)
提交回复
热议问题