Home » Core Java » nio » FileChannel » Save changes to memory mapped ByteBuffer from FileChannel

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Save changes to memory mapped ByteBuffer from FileChannel

In this example we shall show you how to write data to a file using a memory mapped ByteBuffer and a NIO FileChannel in Java. Doing reads and writes of data using Java NIO Channels implies that you should :

  • Create a File object to encapsulate an actual file in the file system
  • Create a random access file stream (read-write). To do so you must first create a RandomAccessFile object to encapsulate the file object created above and open it for read/write operations. Then use the getChannel() API method of the RandomAccessFile object to get the file channel to read/write data from/to
  • Map a region of this channel’s file directly into memory by using the map(MapMode,int,int) API method of the FileChannel class. This method returns a handle to a MappedByteBuffer class for reading/writing data
  • Write data into this buffer at the current position using the put(byte) API method of the MappedByteBuffer class. Do not forget to force() any changes made to this buffer’s contents so as to be written to the storage device containing the mapped file

as described in the code snippet below.

 
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.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class SaveChangesToMemoryMappedByteBufferFromFileChannel {
	
	public static void main(String[] args) {
		
		try {
			
			File file = new File("myfile.dat");
			
			// create a random access file stream (read-write)
		    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
		    
		    // map a region of this channel's file directly into memory
		    MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, (int) channel.size());

		    // write the given byte into this buffer at the current
		    // position, and then increment the position
		    buf.put((byte)0x01);

		    // force any changes made to this buffer's content to be written
		    // to the storage device containing the mapped file
		    buf.force();

		    // close the channel
		    channel.close();
		    
		}
		catch (IOException e) {
			System.out.println("I/O Error: " + e.getMessage());
		}
		
	}

}

This was an example of how to write data to a file using a memory mapped ByteBuffer and a NIO FileChannel in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of