Java I/O How to - Read from Reader and write to Writer until there is no more input from reader








Question

We would like to know how to read from Reader and write to Writer until there is no more input from reader.

Answer

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
/*from   ww w. j a  v  a2 s. co m*/
public class Main {
  /**
   * Read input from reader and write it to writer until there is no more
   * input from reader.
   *
   * @param reader the reader to read from.
   * @param writer the writer to write to.
   * @param buf the char array to use as a bufferx
   */
  public static void flow( Reader reader, Writer writer, char[] buf ) 
      throws IOException {
      int numRead;
      while ( (numRead = reader.read(buf) ) >= 0) {
          writer.write(buf, 0, numRead);
      }
  }
}