Hello to all in forum,
Maybe some java expert could help me.
How can I read chunks from binary file each chunk at a time? The chunks are separated with the
bytes D2 followed by A7 and of variable length. This is whenever D2A7 is found, this is the End/Beginning of a new chunk.
The code I have so far is below and in general does this:
1- Store 1024 bytes in "inputBytes" for each for loop
2- Convert to a hexadecimal string the content of "inputBytes"
3- Replace all the "E8F5" with carriage return \r (in order to be able to use scanner.nextLine feature )
The issue is the last chunk in each iteration of 1024 bytes is incomplete and is needed a way to read 1024
each time and give the offset, but the form "read(inputBytes,Pos,1024)" is not working.
May somebody has an alternative way to do it or how to fix my code. The code is below:
package ReadbyChunks;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;
public class ReadbyChunks {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
File inputFile = new File("./binary");
int lastPos = 0; //To store position of last delimiter
try (InputStream input = new FileInputStream(inputFile)) {
for(int i=1; i<3; i++){ //Loop to read more than one chunk
byte inputBytes[] = new byte[1024];
int readBytes = input.read(inputBytes); // Storing 1024 bytes in "inputBytes"
//Converting to a string the Hexadecimal content of the variable "inputBytes"
String hexstr=DatatypeConverter.printHexBinary(inputBytes);
lastPos=hexstr.lastIndexOf("D2A7")-2; //Storing position of last delimiter
//Replacing all delimiters in "inputBytes" with \r in order to process each chunk
String str = hexstr.replaceAll("D2A7", "\r");
//Now process each "line" (chunk) since they are separated with \r
try (Scanner scanner = new Scanner(str)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// process the line
System.out.println(line);
}
}
}
}
catch (FileNotFoundException ex) {System.err.println("Couldn't read file: " + ex);}
catch (IOException ex) {System.err.println("Error while reading file: " + ex);}
}
}
Thanks in advance