读取字节开始是java二进制文件中的最后一个分隔符位置?
我有一个超过2GB的二进制文件,其中有数百万个块(长度可变),由序列字节0xE8和0x35分隔。 通过询问、调查和尝试,我得到了下面的代码(我不知道这是否有效) 执行时间)。代码的目标是一次处理每个块,我正在尝试这样做:读取字节开始是java二进制文件中的最后一个分隔符位置?,java,binary,delimiter,Java,Binary,Delimiter,我有一个超过2GB的二进制文件,其中有数百万个块(长度可变),由序列字节0xE8和0x35分隔。 通过询问、调查和尝试,我得到了下面的代码(我不知道这是否有效) 执行时间)。代码的目标是一次处理每个块,我正在尝试这样做: 在“inputBytes”中为每个for循环存储1024个字节 将“inputBytes”的内容转换为十六进制字符串 将所有“E8F5”替换为回车符\r(以便能够使用scanner.nextLine功能) 通过这3个步骤,现在我可以处理前1024个字节中的每个块,但要处理第二个
Exception in thread "main" java.lang.IndexOutOfBoundsException
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:246)
at ReadBinaryWithDelimiter.ReadBinaryWithDelimiter.main(ReadBinaryWithDelimiter.java:19)
如何存储1024个字节,从每次迭代的最后一个分隔符位置开始?
这是我目前掌握的代码:
package ReadBinaryWithDelimiter;
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 ReadBinaryWithDelimiter {
public static void main(String[] args) throws FileNotFoundException {
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("E8F5")-2; //Storing position of last delimiter
//Replacing all delimiters in "inputBytes" with \r in order to process each chunk
String str = hexstr.replaceAll("E8F5", "\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);}
}
}
PackageReadBinaryWithDelimiter;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.IOException;
导入java.io.InputStream;
导入java.util.Scanner;
导入javax.xml.bind.DatatypeConverter;
公共类ReadBinaryWithDelimiter{
公共静态void main(字符串[]args)引发FileNotFoundException{
文件输入文件=新文件(“./二进制”);
int lastPos=0;//存储最后一个分隔符的位置
try(InputStream输入=新文件InputStream(inputFile)){
对于(int i=1;i您确定您向我们展示的代码就是导致该异常的代码吗?InputStream的单参数read
方法不应该能够引发IndexOutfBoundsException,但是三参数read
方法可以。Hi VGR.是的。当我仅使用“input.read(inputBytes)”时,它不会显示错误,但当我尝试使用“input.read(inputBytes,lastPos,1024)”时,会出现错误。如何解决此问题以一次读取每个数据块?再次感谢