Reputation: 93
I'm trying something new, There is an application who send data to a memory-mapped file located at Local\MemFileName
I would like to read it in java,
I tried some tutorials like https://www.baeldung.com/java-mapped-byte-buffer, https://howtodoinjava.com/java7/nio/memory-mapped-files-mappedbytebuffer/
But all seem to read a file in JVM, or I did not understand...
How can I read the content of the file Located in windows system Local\MemFileName
Thanks!
Following: Example code of what i tried
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
}
}
}
}
Upvotes: 0
Views: 918
Reputation: 93
The solution for me was to use a WindowsService.class implementing methods from JNA library, as you can see: My Library
With this I could open a file mapped in Windows system.
All the previous answers was correct for a file accessible from JVM, but from outside the JVM it was impossible.
Thanks !
Upvotes: 1
Reputation: 6707
To read a memory mapped file:
Open a FileChannel
on the file using FileChannel.open
.
Invoke the map
method on the FileChannel
to create a MappedByteBuffer
covering the area of the file you want to read.
Read the data from the MappedByteBuffer
.
Upvotes: 1