Java I/O How to - Read from a String value via StringReader








Question

We would like to know how to read from a String value via StringReader.

Answer

 //w  w w.j  av a2s.  co m

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;

public class MainClass {
  public static void main(String[] args) throws IOException {
    try {
      BufferedReader in4 = new BufferedReader(new StringReader("asdf"));
      PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter("IODemo.out")));
      int lineCount = 1;
      String s = null;
      while((s = in4.readLine()) != null )
        out1.println(lineCount++ + ": " + s);
      out1.close();
    } catch(EOFException e) {
      System.err.println("End of stream");
    }

  }
}

The code above generates the following result.