Khashayar
Khashayar

Reputation: 2034

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

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 in Java? in there it said that it's not to possible read a certain line without reading the lines before, but I'm wondering about bytes!

FileReader location = new FileReader(file);
BufferedReader inputFile = new BufferedReader(location);
// Read from bytes 1000 to 2000
// Something like this
inputFile.read(1000,2000);

Is it possible to read certain bytes from a known offset?

Upvotes: 31

Views: 44837

Answers (2)

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.

Upvotes: 18

Woot4Moo
Woot4Moo

Reputation: 24316

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.

Upvotes: 26

Related Questions