java 通过内存映射文件来提高IO读取文件性能

MappedByteBuffer out = new RandomAccessFile("src/demo20/test.dat", "rw").
                getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length);
        for (int i = 0; i < length; i++) {
            out.put((byte)'x');
        }
        System.out.println("end");
        for (int i = length/2; i < length/2+6; i++) {
            System.out.print((char)out.get(i));
        }

先通过RandomAccessFile获取通道,在通过通道的map()产生MappedByteBuffer,设置映射文件的初始位置和映射长度,就可以映射文件的一小部分.

通过这种方式可以提高IO读取文件的性能,因为不必要访问文件的所有大小.

猜你喜欢

转载自www.cnblogs.com/lishuaiqi/p/10629350.html
今日推荐