我在嵌入式Linux设备上使用Java 1.5,并希望读取具有2MB int值的二进制文件. (现在4字节Big Endian,但我可以决定,格式)
通过BufferedInputStream使用DataInputStream使用dis.readInt()),这500,000个调用需要17秒才能读取,但读入一个大字节缓冲区的文件需要5秒.
我怎样才能更快地将该文件读入一个巨大的int []?
读取过程不应超过512 kb.
以下使用nio的代码并不比java io的readInt()方法快.
// asume I already know that there are now 500 000 int to read:
int numInts = 500000;
// here I want the result into
int[] result = new int[numInts];
int cnt = 0;
RandomAccessFile aFile = new RandomAccessFile("filename", "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(512 * 1024);
int bytesRead = inChannel.read(buf); //read into buffer.
while (bytesRead != -1) {
buf.flip(); //make buffer ready for get()
while(buf.hasRemaining() && cnt < numInts){
// probably slow here since called 500 000 times
result[cnt] = buf.getInt();
cnt++;
}
buf.clear(); //make buffer ready for writing
bytesRead = inChannel.read(buf);
}
aFile.close();
inChannel.close();
更新:评估答案:
在PC上,使用IntBuffer方法的内存映射是我设置中最快的.
在嵌入式设备上,没有jit,java.io DataiInputStream.readInt()有点快(17s,与使用IntBuffer的MemMap相比,20s)
定论:
通过算法更改可以更轻松地实现显着的加速. (初始化文件较小)