3

I am making a small program in java, and i want it to read from a set position in a binary file. Like substring only on file streams. Any good way to do this?

byte[] buffer = new byte[1024];   
FileInputStream in = new FileInputStream("test.bin");    
while (bytesRead != -1) {      
    int bytesRead = inn.read(buffer, 0 , buffer.length); 
} 
in.close();
Cœur
  • 37,241
  • 25
  • 195
  • 267
user952725
  • 79
  • 1
  • 4
  • RandomAccessFile might be what you want: http://docs.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html – Ryan Amos Mar 10 '12 at 16:46
  • possible duplicate of [Read a segment of a file in Java / Android](http://stackoverflow.com/questions/3581243/read-a-segment-of-a-file-in-java-android) – Brian Roach Mar 10 '12 at 16:49

3 Answers3

3

One way to do that is to use a java.io.RandomAccessFile and it's java.nio.FileChannel to read and/or write data from/to that file, for example

File file;  // initialize somewhere
ByteBuffer buffer;  // initialize somewhere
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel fc = raf.getChannel();
fc.position(pos);  // position to the byte you want to start reading
fc.read(buffer);  // read data into buffer
byte[] data = buffer.array();
jabu.10245
  • 1,884
  • 1
  • 11
  • 20
1

Use seek to move the stream to the desired start location.

http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#skip(long)

sethcall
  • 2,837
  • 1
  • 19
  • 22
1

I would use RandomAcessFile for the above.

If you are loading a large amount of data I would use memory mapping as this will appear to be much faster (and sometimes it is) BTW You can use FileInputStream for memory mapping as well.

FileChannel in = new FileInputStream("test.bin").getChannel();
MappedByteBuffer mbb = in.map(FileChannel.MapMode, 0, (int) in.size());
// access mbb anywhere
long l = mbb.getLong(40000000); // long at byte 40,000,000
// 
in.close();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130