March 1, 2021
Hot Topics:

Introduction to Memory-Mapped IO in Java

  • By Richard G. Baldwin
  • Send Email »
  • More Articles »

Run the Program

If you haven't already done so, I encourage you to copy the code from Listing 17 into your text editor, compile it, and execute it.  Experiment with it, making changes, and observing the results of your changes.

Remember, however, that you must be running Java version 1.4.0 or later to compile and execute this program.


In this lesson, I have taught you how to use the FileChannel class along with the ByteBuffer class to perform memory-mapped IO for data of type byte.  This is an alternative to the read/write approach discussed in previous lessons.

This lesson teaches the basics of memory-mapped IO using data of type byte.

What's Next?

In the next lesson, I will teach you how to do memory-mapped IO for data records containing mixed types of data.  I will also teach you how to do memory-mapped IO for different data types using different views of the data in a buffer.

Future plans

As time goes on, I plan to publish additional lessons that will help you learn to use other new IO features including:

  • File locks
  • Character-set encoders and decoders
  • Pattern matching on files using regular expressions
  • Socket channels for both clients and servers
  • Non-blocking reads
  • Non-blocking servers

Complete Program Listing

A complete listing of the program discussed in this lesson is shown in Listing 17 below.
/* File Channel04.java
Copyright 2002, R.G.Baldwin

Illustrates use of FileChannel objects
for mapped-memory IO.

First creates and populates a disk
file with data of type byte.

Then creates a memory map of the
existing file, and modifies the map, 
which modifies the contents of the 

Then reads and displays the modified

Then creates a read-only map of part of
the modified file and displays it.

Tested using JDK 1.4.0 under Win2000

The output is:

Data for buf-raw data
65 66 67 68 69 70
Bytes written = 6
Data for mapFile
65 66 67 68 69 70
Data for mod-mapFile
65 66 1 2 69 70
Read/display modified file
Bytes read = 6
Data for newBuf
65 66 1 2 69 70
Data for roMapFile
66 1 2 69

import java.io.*;
import java.nio.channels.*;
import java.nio.*;

class Channel04{  
  public static void main(
                        String[] args){
    //Create and populate an array obj
    byte[] array = {65,66,67,68,69,70};
    //Wrap array in a buffer to create
    // a ByteBuffer object.  Then 
    // display the contents of the
    // buffer.
    ByteBuffer buf = 
    showBufferData(buf,"buf-raw data");
      //Delete the file named junk.txt
      // if it already exists
      new File("junk.txt").delete();
      //Get a channel for writing a
      // random access file in rw
      // mode.
      FileChannel rwCh = (
                  new RandomAccessFile(
      //Write buffer data to the file
                   "Bytes written = " 
                   + rwCh.write(buf));
      //Close the channel so that it
      // can no longer be used to 
      // access the file.
      //Make original ByteBuffer object
      // and original array object
      // eligible for garbage 
      // collection so that their data
      // is no longer accessible.  The
      // data is now available only
      // via the file named junk.txt.
      buf = null;
      array = null;
      //Get a new FileChannel object
      // for reading and writing the 
      // existing file
      rwCh = new RandomAccessFile(

      //Map entire file to memory and
      // close the channel
      long fileSize = rwCh.size();
      ByteBuffer mapFile = rwCh.map(
                          0, fileSize);
      //Display contents of memory map
      //Change contents of the map and
      // hence the file.  Note that
      // the channel is closed.
      //Display new contents of memory
      // map

         "Read/display modified file");
      //Get new channel for read only
      FileChannel newInCh = 
                  new RandomAccessFile(
      //Allocate (don't wrap) a new
      // ByteBuffer
      ByteBuffer newBuf = 

      //Read file data into the new
      // buffer, close the channel, and
      // display the data.
               "Bytes read = " 
               + newInCh.read(newBuf));
      //Get new read-only partial
      // mapping for file and display
      FileChannel rCh = 
                  new RandomAccessFile(
      ByteBuffer roMapFile = rCh.map(
                        1, fileSize-2);
      //Following put throws java.nio.
      // ReadOnlyBufferException, so
      // it is disabled.
    }catch(Exception e){
  }// end main
  static void showBufferData(
          ByteBuffer buf, String name){
    //Displays byte buffer contents
    //Save position
    int pos = buf.position();
    //Set position to zero
            "Data for " + name);
                      buf.get() + " ");
    }//end while loop
    System.out.println();//new line
    //Restore position and return
  }//end showBufferData
}//end class Channel04 definition

Listing 17

Copyright 2002, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects, and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which has gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.



Page 4 of 4

This article was originally published on November 26, 2002

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date