FileChannel

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.

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button