MemMapDemo.java

Download MemMapDemo.java

 1: // Memory Mapped I/O Demo
 2: // If the data file contains the text "ABCDE", running this code
 3: // should change it to "ACCDE".  Note mapped files are only efficient
 4: // for very large files (100K or more).  Here I use a small demo file
 5: // of "ABCDE<CR><NL>"; due to the newline I use print and not println.
 6: // Note there is no automatic way to have an ASCII text file treated
 7: // as an array of char; you are stuck using bytes.  (If you make a
 8: // CharBuffer view, every pair of bytes will be treated as a char,
 9: // not each byte.  This is why the convoluted code for displaying
10: // the before and after views.)
11: //
12: // The memory mapped byte buffer is created ready for reading or
13: // writing.  When closed (on program exit for instance) the data
14: // is flushed from memory to the file; use buf.force() to flush
15: // otherwise.
16: //
17: // Written 6/2009 by Wayne Pollock, Tampa Florida USA
18: 
19: import java.io.*;
20: import java.nio.*;
21: import java.nio.channels.*;
22: 
23: public class MemMapDemo {
24:    private static final String FILE_NAME = "MemMapData.txt";
25: 
26:    public static void main ( String [] args ) throws Exception {
27:       int position = 1;  // Default byte to change (the second)
28: 
29:       // Read position from command line argument, if present:
30:       if ( args != null && args.length == 1 )
31:          position = Integer.parseInt( args[0] );
32: 
33:       // Make sure the file exists (not required in general, just
34:       // for this demo):
35:       File file = new File( FILE_NAME );
36:       if ( ! file.exists() ) {
37:          System.out.println( "Can't open file \"" + FILE_NAME + "\"." );
38:          System.exit(1);
39:       }
40: 
41:       // Create a mapped file byte buffer:
42:       long length = file.length();
43:       MappedByteBuffer buf =
44:          new RandomAccessFile( FILE_NAME, "rw" )
45:            .getChannel()
46:            .map( FileChannel.MapMode.READ_WRITE, 0, length );
47: 
48:       // Display "before" data:
49:       System.out.println( "Buffer capacity, limit: " + buf );
50:       byte [] data = new byte[buf.capacity()];
51:       buf.get( data );
52:       String before = new String( data );
53:       System.out.print( "Before: " + before );
54: 
55:       // Change the position-th byte::
56:       byte c = buf.get( position );
57:       ++c;
58:       buf.put( position, c );
59: 
60:       // Display "after" data:
61:       buf.rewind();
62:       buf.get( data );
63:       String after = new String( data );
64:       System.out.print( "After:  " + after );
65:    }
66: }