Writing to txt file from StringWriter

44.6k Views Asked by At

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());
4

There are 4 best solutions below

2
On BEST ANSWER

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();
0
On

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.

0
On

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
}
0
On

If you don't mind using Apache commons IO :

FileUtils.write(new File("file.txt"), sw.toString(), /*append:*/ true);