Функция FileUtils.writeStringToFile(fileName, text)
для ввода/вывода Apache Commons перезаписывает предыдущий текст в файле. Я хотел бы добавить данные в свой файл. Есть ли способ использовать I/O Commons для того же? Я могу сделать это, используя обычный BufferedWriter
из Java, но мне любопытно относиться к тому же, используя Commons I/O.
Добавление данных в файл с использованием Apache Commons I/O
Ответ 1
Он был реализован в версии 2.1 Apache IO. Чтобы добавить строку в файл, просто передайте true в качестве дополнительного параметра в функциях:
- FileUtils.writeStringToFile
- FileUtils.openOutputStream
- FileUtils.write
- FileUtils.writeByteArrayToFile
- FileUtils.writeLines
Пример:
FileUtils.writeStringToFile(file, "String to append", true);
Ответ 2
Тщательное. Эта реализация, похоже, утечка дескриптора файла...
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() {}
}
Ответ 3
Загрузите последнюю версию Commons-io 2.1
FileUtils.writeStringToFile(File,Data,append)
установите append в true....
Ответ 4
эта маленькая вещь должна сделать трюк:
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: мое затмение было сломано, поэтому оно не показало мне ранее ошибок. исправленные ошибки
Ответ 5
Собственно, версия 2.4 apache-commons-io FileUtils теперь также имеет режим добавления для коллекций.
И зависимость maven:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
<type>jar</type>
</dependency>
Ответ 6
public static void writeStringToFile(File file,
String data,
boolean append)
throws IOException
Writes the toString() value of each item in a collection to the specified File line by line. The default VM encoding and the default line ending will be used.
Parameters:
file - the file to write to
lines - the lines to write, null entries produce blank lines
append - if true, then the lines will be added to the end of the file rather than overwriting
Throws:
IOException - in case of an I/O error
Since:
Commons IO 2.1
Ответ 7
в версии 2.5 вам необходимо передать один дополнительный параметр i.e, encoding.
FileUtils.writeStringToFile(file, "line to append", "UTF-8", true);