Fill and drain a buffer: one element at a time. - Java File Path IO

Java examples for File Path IO:CharBuffer

Description

Fill and drain a buffer: one element at a time.

Demo Code

import java.nio.CharBuffer;

public class Main{
  public static void main(String[] argv) throws Exception {
    CharBuffer buffer = CharBuffer.allocate(100);

    while (fillBuffer(buffer)) {
      buffer.flip();/*from   www .j av a2 s.c  o m*/
      drainBuffer(buffer);
      buffer.clear();
    }
  }

  private static void drainBuffer(CharBuffer buffer) {
    while (buffer.hasRemaining()) {
      System.out.print(buffer.get());
    }
    System.out.println("");
  }

  private static boolean fillBuffer(CharBuffer buffer) {
    if (index >= strings.length) {
      return (false);
    }
    String string = strings[index++];
    for (int i = 0; i < string.length(); i++) {
      buffer.put(string.charAt(i));
    }
    return (true);
  }

  private static int index = 0;

  private static String[] strings = { "1", "2", "3", "4", "5", "6", };
}

Result


Related Tutorials