Writing to txt file from StringWriter

I have a StringWriter, sw variable that is populated by the FreeMarker template. Once I filled sw , how can I print it in a text file?

I have a for loop as follows:

 for(2 times) { template.process(data, sw); out.println(sw.toString()); } 

Now I'm just displaying it. How to do this for a file? I assume that with each cycle my sw will be changed, but I want the data from each cycle to be added together to the file.

Edit: I tried the code below. When it starts, it shows that the file.txt parameter file.txt been changed, but when it restarts, the file still contains nothing.

 sw.append("CheckText"); PrintWriter out = new PrintWriter("file.txt"); out.println(sw.toString()); 
+8
java file-io stringwriter
source share
3 answers

What about

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

and also you can use the output stream, which you can directly pass to template.process(data, os); instead of first writing to StringWriter and then to the file.

See the API doc for template.process(...) to see if such a tool is available.

Reply 2

template.process(Object, Writer) can also accept a FileWriter object, because it is a subclass of Writer, as a parameter, so you can probably do something like this:

 FileWriter fw = new FileWriter("file.txt"); for(2 times) { template.process(data, fw); } fw.close(); 
+13
source share

You can use many different streams to write to a file.

I personally like working with PrintWriter here. You can add a flag to FileWriter (true in the following example):

 try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true))); out.println(sw.toString()); out.close(); } catch (IOException e) { // Do something } 
+2
source share

Why not use FileWriter ?

Open it before the loop and create the required output. When you write to FileWriter, it will add to the buffer and write your accumulated result to close()

Please note that you can open FileWriter in overwrite or add mode so that you can add to existing files.

Here is a simple tutorial .

+1
source share

All Articles