Java - Write text to a file using File Channel

Introduction

The following code converts the text into a byte array.

Then it creates a byte buffer by wrapping the byte array, and writes the buffer to the file channel.

Demo

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) {
    // The output file to write to
    File outputFile = new File("text.txt");

    try (FileChannel fileChannel = new FileOutputStream(outputFile)
        .getChannel()) {/*from  ww w  .j  a v a2s  . c o m*/

      // Get the text as string
      String text = getText();

      // 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("Data has been written to "
          + outputFile.getAbsolutePath());
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }

  public static String getText() {
    String lineSeparator = System.getProperty("line.separator");
    StringBuilder sb = new StringBuilder();
    sb.append("1");
    sb.append(lineSeparator);
    sb.append("2");
    sb.append(lineSeparator);
    sb.append("3");
    sb.append(lineSeparator);
    sb.append("4");

    return sb.toString();
  }
}

Result

To write the data to the storage device immediately, call force(boolean metaData) method.

It flushes the file's contents and metadata to its storage device.

force(false) only writes the file's metadata to the storage device.

force(true) writes the file's content and its metadata are written to the storage device.

Related Topic