Java SeekableByteChannel write to a file

Description

Java SeekableByteChannel write to a file

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;

public class Main {

   public static void main(String[] args) {
      Path path = Paths.get("Main.java");
  
      final String newLine = System.getProperty("line.separator");
      try (SeekableByteChannel sbc = Files.newByteChannel(path, StandardOpenOption.APPEND)) {
         String output = newLine + "Paul" + newLine + "Carol" + newLine + "Fred";
         ByteBuffer buffer = ByteBuffer.wrap(output.getBytes());
         sbc.write(buffer);/*ww w.ja  v  a 2s .  c om*/
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related