Create memory mapped file

This is an example of how to create a memory mapped file in Java. Doing reads and writes of data using Java NIO Channels implies that you should :

as described in the code snippet below.

Want to be a Java NIO Master ?
Subscribe to our newsletter and download the JDBC Ultimate Guide right now!
In order to help you master Java NIO Library, we have compiled a kick-ass guide with all the major Java NIO features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.


 
Do not forget to close the channel after you are done processing the file so as to release operating system resources.
package com.javacodegeeks.snippets.core;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class CreateMemoryMappedFile {
	
	public static void main(String[] args) {
		
		try {
			
			File file = new File("myfile.dat");
			
			// create a random access file stream (for read only)
		    FileChannel readOnlyChannel = new RandomAccessFile(file, "r").getChannel();
		    // map a region of this channel's file directly into memory
		    ByteBuffer readOnlyBuf =
    readOnlyChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) readOnlyChannel.size());
		    // create a random access file stream (read-write)
		    FileChannel readWriteChannel = new RandomAccessFile(file, "rw").getChannel();
		    // map a region of this channel's file directly into memory
		    ByteBuffer readWriteBuf =
  readWriteChannel.map(FileChannel.MapMode.READ_WRITE, 0, (int) readWriteChannel.size());
		    // create a random access file stream (private/copy-on-write))
		    FileChannel privateChannel = new RandomAccessFile(file, "rw").getChannel();
		    // map a region of this channel's file directly into memory
		    ByteBuffer privateBuf =
    privateChannel.map(FileChannel.MapMode.PRIVATE, 0, (int) privateChannel.size());
		    
		}
		catch (IOException e) {
			System.out.println("I/O Error: " + e.getMessage());
		}
		
	}
}

This was an example of how to create a memory mapped file in Java.

Exit mobile version