Java FileChannel write to File

Introduction

Write to a file using NIO FileChannel.

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

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

      try (FileChannel fChan = (FileChannel) Files.newByteChannel(Paths.get("test.txt"), StandardOpenOption.WRITE,
            StandardOpenOption.CREATE)) {
         ByteBuffer mBuf = ByteBuffer.allocate(26);
         for (int i = 0; i < 26; i++)
            mBuf.put((byte) ('A' + i));
         mBuf.rewind();//ww  w.  j  a v  a2s .c  o m
         fChan.write(mBuf);
      } catch (Exception e) {
         System.out.println("I/O Error: " + e);
         System.exit(1);
      }
   }
}



PreviousNext

Related