java mmap写文件,如何在Java中映射(mmap)linux块设备(例如/ dev / sdb)?

I can read/write a linux block device with Java using java.nio. The following code works:

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());

}

However, memory mapping does not work. The following code fails:

MappedByteBuffer mbb = null;

try {

mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, 100);

} catch (IOException e) {

System.out.println("Error mapping file: " + e.getMessage());

}

This fails with Error:

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)

Is there a work around to this? Perhaps by using a different library? I read somewhere that maybe by using JNI I could do this, but I couldn't find any sources.

解决方案

According to the documentation the mechanics of actually mapping a file are left to the implementation. It appears that the implementation is attempting to truncate the file (maybe because the block device size is not the same as the size you specify?).

I am curious why you are reading from the block device directly (unless you are trying to write some sort of filesystem utility or something that needs to do raw I/O). If you need to read from the block device as a memory mapped file directly, you may need to write some C/C++ code to map the file and handle reading/writing to it and use a Java/JNI bridge class to bridge calls to your C/C++ code. That way you handle calling mmap() yourself and can specify any options you need. Looking at the mmap() documentation you may not be able to specify block devices on your platform (I'm guessing Linux but I could be wrong).

If you absolutely need to do this within Java you may need to do read() calls and write() calls of the appropriate length and offset.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值