如何在Java中映射(mmap)linux块设备(例如/ dev / sdb)?
发布时间:2020-05-24 11:20:50 所属栏目:Java 来源:互联网
导读:我可以使用 java.nio读取/编写带有 Java的linux块设备.以下代码有效: Path fp = FileSystems.getDefault().getPath(/dev, sdb);FileChannel fc = null;try { fc = FileChannel.open(fp, EnumSet.of(StandardOpenOption.READ, Stan
|
我可以使用 java.nio读取/编写带有 Java的linux块设备.以下代码有效: Path fp = FileSystems.getDefault().getPath("/dev","sdb");
FileChannel fc = null;
try {
fc = FileChannel.open(fp,EnumSet.of(StandardOpenOption.READ,StandardOpenOption.WRITE));
} catch (Exception e) {
System.out.println("Error opening file: " + e.getMessage());
}
ByteBuffer buf = ByteBuffer.allocate(50);
try {
if(fc != null)
fc.write(buf);
} catch (Exception e) {
System.out.println("Error writing to file: " + e.getMessage());
}
但是,内存映射不起作用.以下代码失败: MappedByteBuffer mbb = null;
try {
mbb = fc.map(FileChannel.MapMode.READ_WRITE,100);
} catch (IOException e) {
System.out.println("Error mapping file: " + e.getMessage());
}
这失败,错误: java.io.IOException: Invalid argument
at sun.nio.ch.FileDispatcherImpl.truncate0(Native Method)
at sun.nio.ch.FileDispatcherImpl.truncate(FileDispatcherImpl.java:79)
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:817)
有没有解决这个问题?也许通过使用不同的库?我在某个地方读过,可能是通过使用JNI,我可以做到这一点,但我找不到任何来源. 解决方法根据 documentation,实际映射文件的机制留给实现.似乎实现正在尝试截断文件(可能是因为块设备大小与您指定的大小不同?).我很好奇为什么你直接从块设备读取(除非你试图编写某种文件系统实用程序或需要做原始I / O的东西).如果需要直接从块设备读取内存映射文件,则可能需要编写一些C/C++代码来映射文件并处理读/写操作并使用Java / JNI桥接类来桥接对您的调用C/C++代码.这样你就可以自己处理调用mmap()并指定你需要的任何选项.看看mmap() documentation你可能无法在你的平台上指定块设备(我猜Linux但我可能错了). 如果您绝对需要在Java中执行此操作,则可能需要执行具有适当长度和偏移量的read()调用和write()调用. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
