我正在尝试新的东西,有一个应用程序将数据发送到位于Local \ MemFileName
的内存映射文件中我想用Java阅读,
我尝试过一些教程,例如https://www.baeldung.com/java-mapped-byte-buffer,https://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
}
}
}
}
读取内存映射文件:
使用FileChannel
在文件上打开FileChannel.open
。
在map
上调用FileChannel
方法以创建一个MappedByteBuffer
来覆盖要读取的文件区域。
从MappedByteBuffer
读取数据。