Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I am generating dynamic page using JSP, I want to save this dynamically generated complete page in file as archive.

In JSP, everything is written to PrintWriter out = response.getWriter();

At the end of page, before sending response to client I want to save this page, either in file or in buffer as string for later treatment.

How can I save Printwriter content or convert to String?

like image 802
superzoom Avatar asked Feb 10 '12 11:02

superzoom


People also ask

How do I get the PrintWriter string?

The write(String) method of PrintWriter Class in Java is used to write the specified String on the stream. This String value is taken as a parameter. Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream. Return Value: This method do not returns any value.

How do you write a StringWriter to a file?

FileWriter fw = new FileWriter("file. txt"); StringWriter sw = new StringWriter(); sw. write("some content..."); fw. write(sw.

Where does PrintWriter write to?

You create the print writer pointing to the system out stream.


2 Answers

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); } 
like image 90
weston Avatar answered Feb 07 '23 08:02

weston


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); 
like image 32
Alvin Bunk Avatar answered Feb 07 '23 08:02

Alvin Bunk