0

我需要读出一个给定的包含 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();
}
4

3 回答 3

3

数组的最大索引大于Integer.MAX_VALUE16000000032大于Integer.MAX_VALUE

Integer.MAX_VALUE = 2^31-1 = 2147483647

2147483647 < 16000000032

您可以通过检查数组是否已满并创建另一个并继续阅读来克服这个问题。但我不太确定您的方法是否是执行此操作的最佳方法。byte[Integer_MAX_VALUE] 是巨大的 ;) 也许你可以将输入文件分割成更小的块来处理它们。

编辑:这就是您可以读取文件的单个 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
}
于 2014-10-23T13:29:44.237 回答
0

I made some progress by starting from scratch! But I still have a problem.

My idea is to read up the first 32 bytes, convert them to a int number. Then the next 32 bytes etc. Unfortunately I just get the first and don't know how to proceed.

I discovered following method for converting these numbers to int:

public static int byteArrayToInt(byte[] b){
    final ByteBuffer bb = ByteBuffer.wrap(b);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    return bb.getInt();
}

so now I have:

    BufferedInputStream in=null;
    byte[] buf = new byte[32];
    try {
        in = new BufferedInputStream(new FileInputStream("ndata.dat"));
        in.read(buf);
        System.out.println(byteArrayToInt(buf));
        in.close();
    } catch (IOException e) {
        System.out.println("error while reading ndata.dat file");
    }
于 2014-10-23T18:44:37.897 回答
0
  1. 如果您需要声明一个大常量,请在其上附加一个“L”,向编译器表明它是一个long常量。但是,正如另一个答案中提到的,您不能声明那么大的数组。
  2. 我怀疑这个练习的目的是学习如何使用java.nio.Buffer系列类。
于 2014-10-23T13:47:39.877 回答