Writing a File with the Old WritableByteChannel Interface - Java File Path IO

Java examples for File Path IO:File Channel

Description

Writing a File with the Old WritableByteChannel Interface

Demo Code

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
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");
    // write a file using WritableByteChannel
    try (WritableByteChannel writableByteChannel = Files.newByteChannel(path,
        EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.APPEND))) {
      ByteBuffer buffer = ByteBuffer.wrap("test test!".getBytes());
      int write = writableByteChannel.write(buffer);
      System.out.println("Number of written bytes: " + write);
      buffer.clear();//from   ww w.jav a2s.c  o m
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials