import java.io.*; import java.nio.IntBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.*; public class Test { public static void main(String[] args){ //LargeMappedFiles.test(); MappedIO.test(); } } class LargeMappedFiles { private static final int length = 0x8000000; //128M public static void test() { try{ MappedByteBuffer out = new RandomAccessFile("./src/data.out","rw") .getChannel() .map(FileChannel.MapMode.READ_WRITE,0,length); for (int i = 0; i < length; i++) { out.put((byte)'c'); } System.out.println("Finished Writting..."); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } abstract class Tester { private String name; public Tester(String name) { this.name=name; } public void runTest(){ System.out.print(name+":"); try{ long start = System.nanoTime(); test(); double duration = System.nanoTime()-start; System.out.format("%.2f\n",duration/1.0e9); } catch (IOException e) { e.printStackTrace(); } } public abstract void test() throws IOException; } class MappedIO { private static int numOfInts = 4000000; private static int numOfBuffInts = 200000; private static Tester[] tests = { new Tester("Stream Write"){ @Override public void test() throws IOException { DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("temp.tmp"))); for (int i = 0; i < numOfInts; i++) { out.writeInt(i); } out.close(); } }, new Tester("Mapped Write") { @Override public void test() throws IOException { FileChannel fc = new RandomAccessFile("temp.tmp","rw") .getChannel(); IntBuffer out = fc .map(FileChannel.MapMode.READ_WRITE,0,fc.size()) .asIntBuffer(); for (int i = 0; i < numOfInts; i++) { out.put(i); } fc.close(); } }, new Tester("Stream Read") { @Override public void test() throws IOException { DataInputStream out = new DataInputStream( new BufferedInputStream( new FileInputStream("temp.tmp"))); for (int i = 0; i < numOfInts; i++) { out.readInt(); } } }, new Tester("Mapped Read") { @Override public void test() throws IOException { FileChannel fc = new RandomAccessFile("temp.tmp","rw") .getChannel(); IntBuffer out = fc .map(FileChannel.MapMode.READ_WRITE,0,fc.size()) .asIntBuffer(); for (int i = 0; i < numOfInts; i++) { out.put(i); } } }, new Tester("Stream Read/Write") { @Override public void test() throws IOException { RandomAccessFile raf = new RandomAccessFile(new File("temp3.tmp"),"rw"); raf.writeInt(1); for (int i = 0; i < numOfBuffInts; i++) { raf.seek(raf.length() - 4); raf.writeInt(raf.readInt()); } } }, new Tester("Mapped Read/Write") { @Override public void test() throws IOException { FileChannel fc = new RandomAccessFile("temp.tmp","rw") .getChannel(); IntBuffer out = fc .map(FileChannel.MapMode.READ_WRITE,0,fc.size()) .asIntBuffer(); out.put(0); for (int i = 1; i < numOfBuffInts; i++) { out.put(out.get(i-1)); } fc.close(); } } }; public static void test() { for (Tester test : tests) { test.runTest(); } } }