Nio如何顺序写文件

  index是上一次写入的位置,该位置需要保存

public static long fileWrite(String filePath, String content, int index) {
     File file = new File(filePath);
     RandomAccessFile randomAccessTargetFile;
     MappedByteBuffer map;
     try {
          randomAccessTargetFile = new RandomAccessFile(file, "rw");
          FileChannel targetFileChannel = randomAccessTargetFile.getChannel();
          map = targetFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, (long) 1024 * 1024 * 1024);
          map.position(index);
          map.put(content.getBytes());
          return map.position();
     } catch (IOException e) {
          e.printStackTrace();
     } finally {
     }
     return 0L;
}

  下面是我写的例子

  下面的例子原来的文件有四个字节的内容,所以映射从offset为4开始

RandomAccessFile randomAccessFile = new RandomAccessFile("d://1.txt", "rw");
        //获取对应的通道
        FileChannel channel = randomAccessFile.getChannel();

        /**
         * 参数1: FileChannel.MapMode.READ_WRITE 使用的读写模式
         * 参数2: 0 : 可以直接修改的起始位置
         * 参数3:  5: 是映射到内存的大小(不是索引位置) ,即将 1.txt 的多少个字节映射到内存
         * 可以直接修改的范围就是 0-5
         * 实际类型 DirectByteBuffer
         */
        MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 4, 5);

        mappedByteBuffer.put(0, (byte) 'H');
        mappedByteBuffer.put(1, (byte) 'O');
        mappedByteBuffer.put(2, (byte) 'T');
        mappedByteBuffer.put(3, (byte) '9');
        mappedByteBuffer.put(4, (byte) 'Y');

  这么搞完文件的内容为 HOT9HOT9Y。前四个字符为之前的内容

posted on 2020-12-22 15:18  MaXianZhe  阅读(239)  评论(0)    收藏  举报

导航