Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from set position in binary file (java)

Tags:

java

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();
like image 887
user952725 Avatar asked Aug 12 '26 04:08

user952725


1 Answers

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();
like image 74
jabu.10245 Avatar answered Aug 13 '26 17:08

jabu.10245