11

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

I have a for loop as follows:

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

Right now, I am just outputting to the screen only. How do I do this for a file? I imagine that with each loop, my sw will get changed, but I want the data from each loop appended together in the file.

Edit: I tried the code below. When it runs, it does show that the file.txt has been changed, but when it reloads, the file still has nothing in it.

sw.append("CheckText");
PrintWriter out = new PrintWriter("file.txt");
out.println(sw.toString());
Community
  • 1
  • 1

4 Answers4

22

How about

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

and also you could consider using an output stream which you can directly pass to template.process(data, os); instead of first writing to a StringWriter then to a file.

Look at the API-doc for the template.process(...) to find out if such a facility is available.

Reply 2

template.process(Object, Writer) can also take a FileWriter object, witch is a subclass of Writer, as parameter, so you probably can do something like that:

FileWriter fw = new FileWriter("file.txt");    
for(2 times)
{
    template.process(data, fw);
}
fw.close();
Fabian
  • 6,973
  • 2
  • 26
  • 27
A4L
  • 17,353
  • 6
  • 49
  • 70
  • It does work but my data gets overwritten every time the loop executes. How do i append data? –  Aug 09 '12 at 12:30
  • 2
    use the other constructor of file writer `FileWriter("file.txt", true)` the second parameter tells taht the data shouldnot be truncated on open, the new content is appended. But in your case you should open the file before the loop and close it once you are done after the loop. – A4L Aug 09 '12 at 12:35
2

You can use many different streams to write to file.

I personally like to work with PrintWriter here You can flag to append in the FileWriter (the 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
}
La bla bla
  • 8,558
  • 13
  • 60
  • 109
1

Why not use a FileWriter ?

Open it before you loop and generate your required output. As you write to the FileWriter it'll append to the buffer and write out your accumulated output upon a close()

Note that you can open a FileWriter in overwrite or append mode, so you can append to existing files.

Here's a simple tutorial.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

If you don't mind using Apache commons IO :

FileUtils.write(new File("file.txt"), sw.toString(), /*append:*/ true);
user1075613
  • 725
  • 9
  • 13