Friday 7 June 2019

Nio: FileChannel: Write to a file


Below step-by-step procedure explains how to write to the file.

Step 1: Get the FileChannel from FileOutputStream.
FileOutputStream fout = new FileOutputStream(filePath)
FileChannel fileChannel = fout.getChannel();

Step 2: Fill the buffer with the content.
byte[] contentBytes = content.getBytes();
ByteBuffer byteBuffer = ByteBuffer.allocate(contentBytes.length);
byteBuffer.put(contentBytes);
byteBuffer.flip();

Step 3: Write the content to the file.
fileChannel.write(byteBuffer);

Find the below working application.

Test.java
package com.sample.app;

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

public class Test {

 private static final String FILE_PATH = "C:\\Users\\krishna\\Documents\\Study\\demo.txt";
 
 public static void writeContentToFile(String content, String filePath) throws FileNotFoundException, IOException {
  if (content == null) {
   return;
  }

  if (filePath == null || filePath.isEmpty()) {
   throw new IllegalArgumentException("filePath shouldn't be null or empty");
  }

  try (FileOutputStream fout = new FileOutputStream(filePath)) {

   byte[] contentBytes = content.getBytes();
   ByteBuffer byteBuffer = ByteBuffer.allocate(contentBytes.length);
   byteBuffer.put(contentBytes);

   FileChannel fileChannel = fout.getChannel();
   byteBuffer.flip();
   fileChannel.write(byteBuffer);
  }

 }

 public static void main(String... args) throws IOException {
  writeContentToFile("Hello, How are you", FILE_PATH);
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment