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

前端 未结 2 1887
难免孤独
难免孤独 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.

提交回复
热议问题