Java FileChannel write ByteBuffer to file

Description

Java FileChannel write ByteBuffer to file

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] args) {
    File file = new File("text.txt");

    try (FileChannel fileChannel = new FileOutputStream(file)
        .getChannel()) {/* w  w  w .  ja v a  2 s  .c om*/

      // Create a ByteBuffer using the byte array
      ByteBuffer buffer = ByteBuffer.wrap(new byte[] {63,64,65,66});

      // Write bytes to the file
      fileChannel.write(buffer);
      System.out.println("written to " + file.getAbsolutePath());
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
}



PreviousNext

Related