Append data into a file using Apache Commons I/O
Solution 1
It has been implemented in 2.1 version of Apache IO. To append string to the file just pass true as an additional parameter in functions:
- FileUtils.writeStringToFile
- FileUtils.openOutputStream
- FileUtils.write
- FileUtils.writeByteArrayToFile
- FileUtils.writeLines
ex:
FileUtils.writeStringToFile(file, "String to append", true);
Solution 2
Download the latest version Commons-io 2.1
FileUtils.writeStringToFile(File,Data,append)
set append to true....
Solution 3
Careful. That implementation seems to be leaking a file handle...
public final class AppendUtils {
public static void appendToFile(final InputStream in, final File f) throws IOException {
OutputStream stream = null;
try {
stream = outStream(f);
IOUtils.copy(in, stream);
} finally {
IOUtils.closeQuietly(stream);
}
}
public static void appendToFile(final String in, final File f) throws IOException {
InputStream stream = null;
try {
stream = IOUtils.toInputStream(in);
appendToFile(stream, f);
} finally {
IOUtils.closeQuietly(stream);
}
}
private static OutputStream outStream(final File f) throws IOException {
return new BufferedOutputStream(new FileOutputStream(f, true));
}
private AppendUtils() {}
}
Solution 4
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
Solution 5
Actually, version 2.4 of apache-commons-io FileUtils now has append mode for collections as well.
And the maven dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
<type>jar</type>
</dependency>
Dexter
Updated on July 23, 2020Comments
-
Dexter almost 4 years
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 normalBufferedWriter
from Java but I'm curious regarding the same using Commons I/O.