【发布时间】:2013-03-31 21:02:31
【问题描述】:
我可以使用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, 0, 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 我可以做到这一点,但我找不到任何来源。
【问题讨论】:
-
那是你的真实代码吗?当然 truncate() 只在只写模式下调用?
标签: java java-native-interface mmap memory-mapping