【问题标题】:Java memory Mapped File from Windows systemWindows系统的Java内存映射文件
【发布时间】:2020-06-05 08:48:18
【问题描述】:

我正在尝试一些新的东西, 有一个应用程序将数据发送到位于 Local\MemFileName

的内存映射文件

我想用java来阅读,

我尝试了一些教程,例如https://www.baeldung.com/java-mapped-byte-bufferhttps://howtodoinjava.com/java7/nio/memory-mapped-files-mappedbytebuffer/

但是好像都是在JVM里读取了一个文件,还是我没看懂……

如何读取位于windows系统Local\MemFileName中的文件内容

谢谢!

以下:我尝试过的示例代码

public class Main {

private static final String IRSDKMEM_MAP_FILE_NAME = StringEscapeUtils.unescapeJava("Local\\IRSDKMemMapFileName");
private static final String IRSDKDATA_VALID_EVENT  = StringEscapeUtils.unescapeJava("Local\\IRSDKDataValidEvent");

public static final CharSequence charSequence = "Local\\IRSDKMemMapFileName";

public static void main(String[] args) throws IOException, InterruptedException {

    System.out.println(charSequence);

    try (RandomAccessFile file = new RandomAccessFile(new File(IRSDKMEM_MAP_FILE_NAME), "r")) {
        //Get file channel in read-only mode
        FileChannel fileChannel = file.getChannel();

        //Get direct byte buffer access using channel.map() operation
        MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());

        // the buffer now reads the file as if it were loaded in memory.
        System.out.println("Loaded " + buffer.isLoaded());  //prints false
        System.out.println("capacity" + buffer.capacity());  //Get the size based on content size of file

        //You can read the file from this buffer the way you like.
        for (int i = 0; i < buffer.limit(); i++) {
            System.out.println((char) buffer.get()); //Print the content of file
        }
    }


}

}

【问题讨论】:

    标签: java memory-mapped-files


    【解决方案1】:

    读取内存映射文件:

    使用FileChannel.open在文件上打开FileChannel

    FileChannel 上调用map 方法以创建一个覆盖您要读取的文件区域的MappedByteBuffer

    MappedByteBuffer读取数据。

    【讨论】:

    • 我做到了,我得到了 NullPointerException。我看到如果我写而不是读,它会在项目目录中创建文件 Local\\MemFileName
    • @JoffreyBonifay 请发布代码以显示您尝试过的内容。
    • 您刚刚发布的代码对我来说很好用!你从哪里得到 NullPointerException?
    • 线程“main”中的异常 java.io.FileNotFoundException: LocalIRSDKMemMapFileName (File not found) at java.io.RandomAccessFile.open0(Native Method) at java.io.RandomAccessFile.open(RandomAccessFile.java :316) 在 java.io.RandomAccessFile.(RandomAccessFile.java:243) 在 io.mappedbus.Main.main(Main.java:21)
    • 文件“Local\\IRSDKMemMapFileName”被应用程序映射到内存中
    【解决方案2】:

    我的解决方案是使用 JNA 库中的 WindowsService.class 实现方法,如您所见: My Library

    这样我就可以打开映射到 Windows 系统中的文件了。

    对于可从 JVM 访问的文件,所有先前的答案都是正确的,但从 JVM 外部这是不可能的。

    谢谢!

    【讨论】:

      猜你喜欢
      • 2011-07-30
      • 2012-07-06
      • 2010-11-01
      • 2012-12-23
      • 2011-05-14
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多