【发布时间】:2020-06-05 08:48:18
【问题描述】:
我正在尝试一些新的东西, 有一个应用程序将数据发送到位于 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
}
}
}
}
【问题讨论】: