Java FileChannel write text to file

Description

Java FileChannel write text 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 ww.jav  a2  s  .  c  om
      String text = "demo from demo2s.com";
      // Convert text into byte array
      byte[] byteData = text.toString().getBytes("UTF-8");

      // Create a ByteBuffer using the byte array
      ByteBuffer buffer = ByteBuffer.wrap(byteData);

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



PreviousNext

Related