javafile-iostringwriter

Writing to txt file from StringWriter


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

Solution

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