集册 Java实例教程 三种记忆

三种记忆

欢马劈雪     最近更新时间:2020-01-02 10:19:05

453
  • FileChannel.MapMode.READ_ONLY
  • FileChannel.MapMode.READ_WRITE
  • FileChannel.MapMode.PRIVATE
  

import java.io.File;

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;

import java.nio.MappedByteBuffer;//时 代 J a v a 提供

import java.nio.channels.FileChannel;


public class Main {

  public static void main(String[] argv) throws Exception {

    File tempFile = File.createTempFile("test", null);

    RandomAccessFile file = new RandomAccessFile(tempFile, "rw");

    FileChannel channel = file.getChannel();

    ByteBuffer temp = ByteBuffer.allocate(100);


    temp.put("This is the file content".getBytes());

    temp.flip();

    channel.write(temp, 0);


    temp.clear();

    temp.put("This is more file content".getBytes());

    temp.flip();

    channel.write(temp, 8192);/*来 自 n  o  w  j  a  v  a . c o m*/


    MappedByteBuffer ro = channel.map(FileChannel.MapMode.READ_ONLY, 0,

        channel.size());

    MappedByteBuffer rw = channel.map(FileChannel.MapMode.READ_WRITE, 0,

        channel.size());

    MappedByteBuffer cow = channel.map(FileChannel.MapMode.PRIVATE, 0,

        channel.size());


    System.out.println("Begin");

    showBuffers(ro, rw, cow);

    cow.position(8);

    cow.put("test".getBytes());

    showBuffers(ro, rw, cow);

    rw.position(9);

    rw.put(" 11 ".getBytes());

    rw.position(8194);

    rw.put(" 22 ".getBytes());

    rw.force();

    showBuffers(ro, rw, cow);



    temp.clear();

    temp.put("Channel write ".getBytes());

    temp.flip();

    channel.write(temp, 0);

    temp.rewind();

    channel.write(temp, 8202);


    showBuffers(ro, rw, cow);

    cow.position(8207);

    cow.put(" COW2 ".getBytes());


    showBuffers(ro, rw, cow);


    rw.position(0);

    rw.put(" 22 ".getBytes());

    rw.position(8210);

    rw.put(" 22 ".getBytes());

    rw.force();


    showBuffers(ro, rw, cow);


    channel.close();

    file.close();

    tempFile.delete();

  }

  public static void showBuffers(ByteBuffer ro, ByteBuffer rw, ByteBuffer cow)

      throws Exception {

    dumpBuffer("R/O", ro);

    dumpBuffer("R/W", rw);

    dumpBuffer("COW", cow);

    System.out.println("");

  }

  public static void dumpBuffer(String prefix, ByteBuffer buffer)

      throws Exception {

    System.out.print(prefix + ": '");

    int nulls = 0;

    int limit = buffer.limit()
展开阅读全文