Replace a File Portion with Truncate Capability using SeekableByteChannel - Java File Path IO

Java examples for File Path IO:File Channel

Description

Replace a File Portion with Truncate Capability using 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 buffer = ByteBuffer.wrap("this is a test.".getBytes());
    try (SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path,
        EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE)))) {
      seekableByteChannel.truncate(200);
      seekableByteChannel.position(seekableByteChannel.size() - 1);
      while (buffer.hasRemaining()) {
        seekableByteChannel.write(buffer);
      }//from  w w  w . j a  v a  2  s.  c  o  m
      buffer.clear();
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials