从文件小尾数整数快速阅读尾数、整数、快速、文件

2023-09-05 04:14:00 作者:情深似海不如沉入大海

我需要阅读的二进制文件组成的4个字节的整数(小端)到一个二维数组我的Andr​​oid应用程序。我目前的解决方案如下:

I need to read a binary file consisting of 4 byte integers (little endian) into a 2D array for my Android application. My current solution is the following:

DataInputStream inp = null;
try {
    inp = new DataInputStream(new BufferedInputStream(new FileInputStream(procData), 32768));
}
catch (FileNotFoundException e) {
    Log.e(TAG, "File not found");
}

int[][] test_data = new int[SIZE_X][SIZE_Y];
byte[] buffer = new byte[4];
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
for (int i=0; i < SIZE_Y; i++) {
    for (int j=0; j < SIZE_X; j++) {
        inp.read(buffer);
        byteBuffer = ByteBuffer.wrap(buffer);
        test_data[j][SIZE_Y - i - 1] = byteBuffer.order(ByteOrder.LITTLE_ENDIAN).getInt();
    }
}

这是pretty的一个2K * 2K阵列慢,大约需要25秒。我可以在DDMS垃圾收集器正在加班看,所以这可能是一个原因进展缓慢。

This is pretty slow for a 2k*2k array, it takes about 25 seconds. I can see in the DDMS that the garbage collector is working overtime, so that is probably one reason for the slowness.

必须有使用的ByteBuffer来读取该文件到阵列中的一个更有效的方式,但我不是现在看到它。就如何加快这你知道吗?

There has to be a more efficient way of using the ByteBuffer to read that file into the array, but I'm not seeing it at the moment. Any idea on how to speed this up?

推荐答案

为什么不读入4个字节的缓冲区,然后手动重新排列字节?它看起来是这样的:

Why not read into a 4-byte buffer and then rearrange the bytes manually? It will look like this:

for (int i=0; i < SIZE_Y; i++) {
    for (int j=0; j < SIZE_X; j++) {
        inp.read(buffer);
        int nextInt = (buffer[0] & 0xFF) | (buffer[1] & 0xFF) << 8 | (buffer[2] & 0xFF) << 16 | (buffer[3] & 0xFF) << 24;
        test_data[j][SIZE_Y - i - 1] = nextInt;
    }
}

当然,假定读取所有四个字节,但你应该检查的情况时,它不是。这样,你就不会在读取过程中(等垃圾收集器没有应变),你不叫什么,你只需要使用位运算创建任何对象。

Of course, it is assumed that read reads all four bytes, but you should check for the situation when it's not. This way you won't create any objects during reading (so no strain on the garbage collector), you don't call anything, you just use bitwise operations.

 
精彩推荐