Writing a File with SeekableByteChannel - Java File Path IO

Java examples for File Path IO:File Channel

Description

Writing a File 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/folder0/folder8", "story.txt");
    try (SeekableByteChannel seekableByteChannel = Files.newByteChannel(path,
        EnumSet.of(StandardOpenOption.WRITE,
            StandardOpenOption.TRUNCATE_EXISTING))) {
      ByteBuffer buffer = ByteBuffer.wrap("this is a test".getBytes());
      int write = seekableByteChannel.write(buffer);
      System.out.println("Number of written bytes: " + write);
      buffer.clear();/* w w w  .ja  v a2 s. c  o m*/
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result

  • To write into a file that exists, at the beginning, use WRITE
  • To write into a file that exists, at the end, use WRITE and APPEND
  • To write into a file that exists and clean up its content before writing, use WRITE and TRUNCATE_EXISTING
  • To write into a file that does not exist, use CREATE (or CREATE_NEW) and WRITE

Related Tutorials