Write Characters at Different Positions with SeekableByteChannel - Java File Path IO

Java examples for File Path IO:File Channel

Description

Write Characters at Different Positions with SeekableByteChannel

Demo Code

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
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// ww w.j  av a2  s . co  m
        .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());
      while (buffer_1.hasRemaining()) {
        seekableByteChannel.write(buffer_1);
      }
      seekableByteChannel.position(301);
      while (buffer_2.hasRemaining()) {
        seekableByteChannel.write(buffer_2);
      }
      buffer_1.clear();
      buffer_2.clear();
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials