how to convert PrintWriter to String or write to a File?

To get a string from the output of a PrintWriter, you can pass a StringWriter to a PrintWriter via the constructor:

@Test
public void writerTest(){
    StringWriter out    = new StringWriter();
    PrintWriter  writer = new PrintWriter(out);

    // use writer, e.g.:
    writer.print("ABC");
    writer.print("DEF");

    writer.flush(); // flush is really optional here, as Writer calls the empty StringWriter.flush
    String result = out.toString();

    assertEquals("ABCDEF", result);
}

Why not use StringWriter instead? I think this should be able to provide what you need.

So for example:

StringWriter strOut = new StringWriter();
...
String output = strOut.toString();
System.out.println(output);