|
| 1 | +package basic.nio; |
| 2 | + |
| 3 | +import java.io.BufferedOutputStream; |
| 4 | +import java.io.DataOutputStream; |
| 5 | +import java.io.File; |
| 6 | +import java.io.FileOutputStream; |
| 7 | +import java.io.IOException; |
| 8 | +import java.io.RandomAccessFile; |
| 9 | +import java.nio.channels.FileChannel; |
| 10 | +import java.nio.IntBuffer; |
| 11 | + |
| 12 | +public class MappedIO { |
| 13 | + private static int numOfInts = 4000000; |
| 14 | + private static int numOfUbuffInts = 200000; |
| 15 | + |
| 16 | + private abstract static class Testter { |
| 17 | + private String name; |
| 18 | + |
| 19 | + public Testter(String name) { |
| 20 | + this.name = name; |
| 21 | + } |
| 22 | + |
| 23 | + public void runTest() { |
| 24 | + try { |
| 25 | + long start = System.nanoTime(); |
| 26 | + test(); |
| 27 | + double duration = System.nanoTime() - start; |
| 28 | + System.out.format("%.2f\n", duration / 1.0e9); |
| 29 | + } catch (IOException e) { |
| 30 | + throw new RuntimeException(e); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + public abstract void test() throws IOException; |
| 35 | + } |
| 36 | + private static Testter[] tests={ |
| 37 | + new Testter("Stream Write"){ |
| 38 | + @Override |
| 39 | + public void test() throws IOException { |
| 40 | + DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File("temp.tmp")))); |
| 41 | + for(int i=0;i<numOfInts;i++){ |
| 42 | + dos.writeInt(1); |
| 43 | + } |
| 44 | + dos.close(); |
| 45 | + } |
| 46 | + }, |
| 47 | + new Testter("Mapped Writer"){ |
| 48 | + @Override |
| 49 | + public void test() throws IOException { |
| 50 | + FileChannel fc=new RandomAccessFile("temp.tmp","rw").getChannel(); |
| 51 | + IntBuffer ib=fc.map(FileChannel.MapMode.READ_WRITE,0,fc.size()).asIntBuffer(); |
| 52 | + for(int i=0;i<numOfInts;i++) |
| 53 | + ib.put(i); |
| 54 | + fc.close(); |
| 55 | + } |
| 56 | + } |
| 57 | + }; |
| 58 | +} |
0 commit comments