views:

161

answers:

1

The FileUtils.writeStringToFile(fileName, text) function of Apache Commons I/O overwrites previous text in a file. I would like to append data to my file. Is there any way I could use Commons I/O for the same? I can do it using normal BufferedWriter from Java but I'm curious regarding the same using Commons I/O.

A: 

this little thingy should do the trick:

package com.yourpackage;

// you're gonna want to optimize these imports
import java.io.*;
import org.apache.commons.io.*;

public final class AppendUtils {

    public static void appendToFile(final InputStream in, final File f)
            throws IOException {
        IOUtils.copy(in, outStream(f));
    }

    public static void appendToFile(final String in, final File f)
            throws IOException {
        appendToFile(IOUtils.toInputStream(in), f);
    }

    private static OutputStream outStream(final File f) throws IOException {
        return new BufferedOutputStream(new FileOutputStream(f, true));
    }

    private AppendUtils() {
    }

}

edit: my eclipse was broken, so it didn't show me the errors earlier. fixed errors

seanizer
Seanizer, Thanks mate !
Denzil