October 30, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Introduction to Memory-Mapped IO in Java

  • November 26, 2002
  • 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.

Summary

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 
file.

Then reads and displays the modified
file.

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 = 
                ByteBuffer.wrap(array);
    showBufferData(buf,"buf-raw data");
        
    try{
      //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(
                     "junk.txt","rw")).
                          getChannel();
                          
      //Write buffer data to the file
      System.out.println(
                   "Bytes written = " 
                   + rwCh.write(buf));
                   
      //Close the channel so that it
      // can no longer be used to 
      // access the file.
      rwCh.close();
                   
      //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(
                      "junk.txt","rw").
                          getChannel();

      //Map entire file to memory and
      // close the channel
      long fileSize = rwCh.size();
      ByteBuffer mapFile = rwCh.map(
        FileChannel.MapMode.READ_WRITE,
                          0, fileSize);
      rwCh.close();
      
      //Display contents of memory map
      showBufferData(
                    mapFile,"mapFile");
      //Change contents of the map and
      // hence the file.  Note that
      // the channel is closed.
      mapFile.position(2);
      mapFile.put((byte)1);
      mapFile.put((byte)2);
      
      //Display new contents of memory
      // map
      showBufferData(
                mapFile,"mod-mapFile");

      System.out.println(
         "Read/display modified file");
      //Get new channel for read only
      FileChannel newInCh = 
                  new RandomAccessFile(
                       "junk.txt","r").
                          getChannel();
                          
      //Allocate (don't wrap) a new
      // ByteBuffer
      ByteBuffer newBuf = 
                   ByteBuffer.allocate(
                        (int)fileSize);

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

Baldwin@DickBaldwin.com

-end-
 



Page 4 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel