我需要读出包含 500000001 个二进制文件的给定大文件。之后我必须将它们翻译成 ASCII。
我的问题是在尝试将二进制文件存储在大型数组中时发生的。我在数组 ioBuf 的定义处收到警告:
“int 类型的文字 16000000032 超出范围。”
我不知道如何保存这些数字来使用它们!有人有想法吗?
这是我的代码:
public byte[] read(){
try{
BufferedInputStream in = new BufferedInputStream(new FileInputStream("data.dat"));
ByteArrayOutputStream bs = new ByteArrayOutputStream();
BufferedOutputStream out = new BufferedOutputStream(bs);
byte[] ioBuf = new byte[16000000032];
int bytesRead;
while ((bytesRead = in.read(ioBuf)) != -1){
out.write(ioBuf, 0, bytesRead);
}
out.close();
in.close();
return bs.toByteArray();
}
最佳答案
数组的最大索引为 Integer.MAX_VALUE
并且 16000000032
大于 Integer.MAX_VALUE
Integer.MAX_VALUE = 2^31-1 = 2147483647
2147483647 < 16000000032
您可以通过检查数组是否已满并创建另一个数组并继续阅读来克服这个问题。 但我不太确定你的方法是否是执行此操作的最佳方法。 byte[Integer_MAX_VALUE] 很大;) 也许您可以将输入文件分割成更小的 block 来处理它们。
编辑:这是读取文件的单个 int 的方法。您可以将缓冲区的大小调整为您想要读取的数据量。但您试图立即读取整个文件。
//Allocate buffer with 4byte = 32bit = Integer.SIZE
byte[] ioBuf = new byte[4];
int bytesRead;
while ((bytesRead = in.read(ioBuf)) != -1){
//if bytesRead == 4 you read 1 int
//do your stuff
}
关于java:读取大型二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26529205/