集册 Java实例教程 使用SeekableByteChannel在不同位置写入字符

使用SeekableByteChannel在不同位置写入字符

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

675
使用SeekableByteChannel在不同位置写入字符

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.SeekableByteChannel;

import java.nio.file.Files;// from N o w J a v a . c o m - 时代Java

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.util.EnumSet;


public class Main {

  public static void main(String[] args) {


    Path path = Paths

        .get("C:/folder1/folder2/folder4", "test.txt");

    ByteBuffer buffer_1 = ByteBuffer.wrap("this is a test.".getBytes());

    ByteBuffer buffer_2 = ByteBuffer.wrap("test".getBytes());

    try (SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path,

        EnumSet.of(StandardOpenOption.WRITE)))) {

      seekableByteChannel.position(seekableByteChannel.size());
      /**
       * nowjava - 时  代  Java 提 供 
      **/

      while (buffer_1.hasRemaining()) {

        seekableByteChannel.write(buffer_1);

      }

      seekableByteChannel.position(301);
展开阅读全文