importjava.io.File;importjava.io.IOException;importjava.io.RandomAccessFile;importjava.nio.CharBuffer;importjava.nio.channels.FileChannel;importjava.nio.channels.FileChannel.MapMode;public classmemorymapfiledemo {final static String filepath = "/home/hadoop/test/java.txt";public static void main(String[] args) throwsIOException {
writefile(filepath);
readfile(filepath);
}static void writefile(String _filepath) throwsIOException {
File _file= newFile(_filepath);
RandomAccessFile raf= new RandomAccessFile(_file, "rw");
FileChannel fc=raf.getChannel();int buffersize = 1024 * 8;
CharBuffer cb= fc.map(MapMode.READ_WRITE, 0, buffersize)
.asCharBuffer();
String lineseperator=java.security.AccessController
.doPrivileged(newsun.security.action.GetPropertyAction("line.separator"));
String content= "";long offset = 0;for (int i = 1; i <= 1000; i++) {
content= "Line" + i + " hello java" +lineseperator;if ((cb.limit() - cb.position())
offset+=cb.position();
cb=fc.map(MapMode.READ_WRITE, offset, buffersize)
.asCharBuffer();
}
cb.put(content);
}
fc.close();
raf.close();
}static void readfile(String _filepath) throwsIOException {
File _file= newFile(_filepath);
RandomAccessFile raf= new RandomAccessFile(_file, "rw");
FileChannel fc=raf.getChannel();long totalsize =fc.size();int buffersize = 1024 * 8;long offset = 0;
CharBuffer cb= fc.map(MapMode.READ_ONLY, 0, buffersize).asCharBuffer();while (offset
System.out.print(cb.get());
}
offset+=cb.position();
cb=fc.map(MapMode.READ_ONLY, offset, buffersize).asCharBuffer();
}
fc.close();
raf.close();
}
}