Java I/O How to - Write A String As Bytes via FileChannel








Question

We would like to know how to write A String As Bytes via FileChannel.

Answer

//from  ww w .  java 2 s  .  c o m

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

public class MainClass {
  public static void main(String[] args) {

    String phrase = new String("www.java2s.com API \n");
    File aFile = new File("test.txt");

    FileOutputStream file = null;
    try {
      file = new FileOutputStream(aFile, true);
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
    FileChannel outChannel = file.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(phrase.length());
    byte[] bytes = phrase.getBytes();
    buf.put(bytes);
    buf.flip();

    try {
      outChannel.write(buf);
      file.close();
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}

The code above generates the following result.