Java I/O How to - Use New Java IO to write string into a file








Question

We would like to know how to use New Java IO to write string into a file.

Answer

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/*from   ww w .  j  a va  2 s  . c  o m*/
public class Main{
  public static void main(String[] args) throws Exception{
    String phrase = new String("www.java2s.com\n");

    File aFile = new File("test.txt");   
    FileOutputStream outputFile = null;  
    outputFile = new FileOutputStream(aFile, true);
    System.out.println("File stream created successfully.");

    FileChannel outChannel = outputFile.getChannel();
    
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("New buffer:           position = " + buf.position()
                       + "\tLimit = " + buf.limit() + "\tcapacity = "
                       + buf.capacity());
    // Load the data into the buffer
    for (char ch : phrase.toCharArray()) {
      buf.putChar(ch);
    }
    System.out.println("Buffer after loading: position = " + buf.position()
                       + "\tLimit = " + buf.limit() + "\tcapacity = "
                       + buf.capacity());
    buf.flip();
    System.out.println("Buffer after flip:    position = " + buf.position() 
                       + "\tLimit = " + buf.limit() + "\tcapacity = " 
                       + buf.capacity());

    outChannel.write(buf);
    outputFile.close();
    System.out.println("Buffer contents written to file.");
  }
}

The code above generates the following result.