Java Tutorial/File/Buffer

Материал из Java эксперт
Перейти к: навигация, поиск

Using a Formatter Object to Load a Buffer

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.util.Formatter;
public class MainClass {
  public static void main(String[] args) {
    String[] phrases = { "A", "B 1", "C 1.3" };
    String dirname = "C:/test";
    String filename = "Phrases.txt";
    File dir = new File(dirname);
    File aFile = new File(dir, filename);
    FileOutputStream outputFile = null;
    try {
      outputFile = new FileOutputStream(aFile, true);
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
    FileChannel outChannel = outputFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    CharBuffer charBuf = buf.asCharBuffer();
    System.out.println(charBuf.position());
    System.out.println(charBuf.limit());
    System.out.println(charBuf.capacity());
    Formatter formatter = new Formatter(charBuf);
    int number = 0;
    for (String phrase : phrases) {
      formatter.format("%n %s", ++number, phrase);
      System.out.println(charBuf.position());
      System.out.println(charBuf.limit());
      System.out.println(charBuf.capacity());
      charBuf.flip();
      System.out.println(charBuf.position());
      System.out.println(charBuf.limit());
      System.out.println(charBuf.length());
      buf.limit(2 * charBuf.length()); // Set byte buffer limit
      System.out.println(buf.position());
      System.out.println(buf.limit());
      System.out.println(buf.remaining());
      try {
        outChannel.write(buf);
        buf.clear();
        charBuf.clear();
      } catch (IOException e) {
        e.printStackTrace(System.err);
      }
    }
    try {
      outputFile.close();
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}