我需要在Java中反复向现有文件追加文本。我怎么做呢?


当前回答

/**********************************************************************
 * it will write content to a specified  file
 * 
 * @param keyString
 * @throws IOException
 *********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
    // For output to file
    File a = new File(textFilePAth);

    if (!a.exists()) {
        a.createNewFile();
    }
    FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(keyString);
    bw.newLine();
    bw.close();
}// end of writeToFile()

其他回答

FileOutputStream stream = new FileOutputStream(path, true);
try {

    stream.write(

        string.getBytes("UTF-8") // Choose your encoding.

    );

} finally {
    stream.close();
}

然后在上游某处捕获IOException。

使用Apache Commons 2.1:

import org.apache.logging.log4j.core.util.FileUtils;

FileUtils.writeStringToFile(file, "String to append", true);
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

true允许在现有文件中追加数据。如果我们写

FileOutputStream fos = new FileOutputStream("File_Name");

它将覆盖现有文件。所以选择第一种方法。

在Java-7中也可以这样做:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

//---------------------

Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
    Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);

您可以使用fileWriter将标志设置为true,用于追加。

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}