Copy a Portion of a File from the Beginning to the End with SeekableByteChannel - Java File Path IO

Java examples for File Path IO:File Channel

Description

Copy a Portion of a File from the Beginning to the End 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.get("C:/folder1/folder2/folder4", "test.txt");
    ByteBuffer copy = ByteBuffer.allocate(25);
    copy.put("\ntest".getBytes());
    try (SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path,
        EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE)))) {
      int nbytes;
      do {//  w  w w . j a  va 2s .c o  m
        nbytes = seekableByteChannel.read(copy);
      } while (nbytes != -1 && copy.hasRemaining());
      copy.flip();
      seekableByteChannel.position(seekableByteChannel.size());
      while (copy.hasRemaining()) {
        seekableByteChannel.write(copy);
      }
      copy.clear();

    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials