/home/wpollock1/public_html/AJava/MemMapDemo.java
// Memory Mapped I/O Demo
// If the data file contains the text "ABCDE", running this code
// should change it to "ACCDE". Note mapped files are only efficient
// for very large files (100K or more). Here I use a small demo file
// of "ABCDE<CR><NL>"; due to the newline I use print and not println.
// Note there is no automatic way to have an ASCII text file treated
// as an array of char; you are stuck using bytes. (If you make a
// CharBuffer view, every pair of bytes will be treated as a char,
// not each byte. This is why the convoluted code for displaying
// the before and after views.)
//
// The memory mapped byte buffer is created ready for reading or
// writing. When closed (on program exit for instance) the data
// is flushed from memory to the file; use buf.force() to flush
// otherwise.
//
// Written 6/2009 by Wayne Pollock, Tampa Florida USA
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class MemMapDemo {
private static final String FILE_NAME = "MemMapData.txt";
public static void main ( String [] args ) throws Exception {
int position = 1; // Default byte to change (the second)
// Read position from command line argument, if present:
if ( args != null && args.length == 1 )
position = Integer.parseInt( args[0] );
// Make sure the file exists (not required in general, just
// for this demo):
File file = new File( FILE_NAME );
if ( ! file.exists() ) {
System.out.println( "Can't open file \"" + FILE_NAME + "\"." );
System.exit(1);
}
// Create a mapped file byte buffer:
long length = file.length();
MappedByteBuffer buf =
new RandomAccessFile( FILE_NAME, "rw" )
.getChannel()
.map( FileChannel.MapMode.READ_WRITE, 0, length );
// Display "before" data:
System.out.println( "Buffer capacity, limit: " + buf );
byte [] data = new byte[buf.capacity()];
buf.get( data );
String before = new String( data );
System.out.print( "Before: " + before );
// Change the position-th byte::
byte c = buf.get( position );
++c;
buf.put( position, c );
// Display "after" data:
buf.rewind();
buf.get( data );
String after = new String( data );
System.out.print( "After: " + after );
}
}