簡體   English   中英

Java memory 映射文件來自 Windows 系統

[英]Java memory Mapped File from Windows system

我正在嘗試一些新的東西,有一個應用程序將數據發送到位於 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
        }
    }


}

}

要讀取 memory 映射文件:

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

FileChannel上調用map方法以創建一個MappedByteBuffer覆蓋您要讀取的文件區域。

MappedByteBuffer讀取數據。

我的解決方案是使用 WindowsService.class 實現 JNA 庫中的方法,如您所見: 我的庫

有了這個,我可以打開一個映射在 Windows 系統中的文件。

對於可從 JVM 訪問的文件,所有先前的答案都是正確的,但從 JVM 外部這是不可能的。

謝謝 !

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM