Using a Channel to Write a String to a File : FileChannel « File « Java Tutorial






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("text \n");
    String dirname = "C:/test"; 
    String filename = "charData.txt"; 
    File dir = new File(dirname); 
    File aFile = new File(dir, filename); 
    FileOutputStream outputFile = null; 
    try {
      outputFile = new FileOutputStream(aFile, true);
      System.out.println("File stream created successfully.");
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
    FileChannel outChannel = outputFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("New buffer:           position = " + buf.position() + "\tLimit = "
        + buf.limit() + "\tcapacity = " + buf.capacity());
    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());
    try {
      outChannel.write(buf);
      outputFile.close(); 
      System.out.println("Buffer contents written to file.");
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}








11.51.FileChannel
11.51.1.Get FileChannel from FileInputStream
11.51.2.Using FileChannel to read text file
11.51.3.Using FileChannel to random access to a File
11.51.4.Writing and Appending a ByteBuffer to a File
11.51.5.A channel for a physical file
11.51.6.Using a Channel to Write a String to a File
11.51.7.Writing a String as Bytes
11.51.8.Writing Varying Length Strings to a File
11.51.9.Writing Numerical Data to a File
11.51.10.Writing Mixed Data to a File
11.51.11.The Gathering Write
11.51.12.Copying Files using FileChannel
11.51.13.New IO Copier
11.51.14.New IO Duplicator
11.51.15.Locking Copier
11.51.16.File concatenation based on new IO
11.51.17.New IO Transfer
11.51.18.Save and read text using FileChannel with UTF-16BE encoding
11.51.19.Save and read text using FileChannel without encoding
11.51.20.Using transferTo() between channels
11.51.21.Test overlapping locks on different file channels
11.51.22.Lock a FileChannel and release the lock
11.51.23.Create a read-only memory-mapped file
11.51.24.Create a read-write memory-mapped file
11.51.25.Copying a file using channels and buffers