我需要将一个由 4 字节整数(小端)组成的二进制文件读入我的 Android 应用程序的二维数组中。我目前的解决方案如下:
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();
}
}
这对于 2k*2k 数组来说相当慢,大约需要 25 秒。我可以在 DDMS 中看到垃圾收集器正在超时工作,所以这可能是速度缓慢的原因之一。
必须有一种更有效的方法来使用 ByteBuffer 将该文件读入数组,但我目前没有看到它。关于如何加快速度的任何想法?
最佳答案
为什么不读入一个 4 字节的缓冲区,然后手动重新排列字节?它看起来像这样:
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;
}
}
当然,假设read
读取了所有四个字节,但如果不是,您应该检查一下情况。这样您就不会在读取期间创建任何对象(因此不会对垃圾收集器造成压力),您不会调用任何东西,您只需使用按位运算。
关于java - 从文件中快速读取小端整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5078100/