Apache Commons I/OのFileUtils.writeStringToFile(fileName, text)
機能は、ファイル内の以前のテキストを上書きします。ファイルにデータを追加したいと思います。同じために Commons I/O を使用する方法はありますか? 私は Java から通常の方法でそれを行うことができますBufferedWriter
が、Commons I/O を使用して同じことについて興味があります。
44817 次
7 に答える
65
Apache IO の 2.1 バージョンで実装されています。ファイルに文字列を追加するには、関数の追加パラメーターとしてtrueを渡すだけです。
- FileUtils.writeStringToFile
- FileUtils.openOutputStream
- FileUtils.write
- FileUtils.writeByteArrayToFile
- FileUtils.writeLines
元:
FileUtils.writeStringToFile(file, "String to append", true);
于 2011-11-28T10:44:11.893 に答える
5
最新バージョン Commons-io 2.1 をダウンロード
FileUtils.writeStringToFile(File,Data,append)
追加をtrueに設定....
于 2011-12-02T13:44:12.267 に答える
4
気をつけろ。その実装はファイルハンドルをリークしているようです...
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() {}
}
于 2011-03-12T00:26:32.943 に答える
2
この小さなことはトリックを行う必要があります:
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() {
}
}
編集:私の日食が壊れていたので、以前はエラーが表示されませんでした。修正されたエラー
于 2010-06-04T08:50:15.433 に答える
0
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
于 2011-11-28T11:03:05.887 に答える