我已经为特定的二进制格式编写了一个解析器类(nfdump,如果有人感兴趣的话),它使用java.nio的MappedByteBuffer来读取每个几GB的文件.二进制格式只是一系列标题和大多数固定大小的二进制记录,它们通过调用nextRecord()输出到被调用者,后者推送状态机,在完成时返回null.它表现很好.它适用于开发机器.
在我的生产主机上,它可以运行几分钟或几小时,但似乎总是抛出"java.lang.InternalError:在编译的Java代码中最近的一个不安全的内存访问操作中发生了一个错误",指法其中一个Map.getInt ,getShort方法,即地图中的读取操作.
设置地图的无争议(?)代码是这样的:
/** Set up the map from the given filename and position */
protected void open() throws IOException {
// Set up buffer, is this all the flexibility we'll need?
channel = new FileInputStream(file).getChannel();
MappedByteBuffer map1 = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
map1.load(); // we want the whole thing, plus seems to reduce frequency of crashes?
map = map1;
// assumes the host writing the files is little-endian (x86), ought to be configurable
map.order(java.nio.ByteOrder.LITTLE_ENDIAN);
map.position(position); …Run Code Online (Sandbox Code Playgroud)