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


当前回答

FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

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

FileOutputStream fos = new FileOutputStream("File_Name");

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

其他回答

用番石榴做的样品:

File to = new File("C:/test/test.csv");

for (int i = 0; i < 42; i++) {
    CharSequence from = "some string" + i + "\n";
    Files.append(from, to, Charsets.UTF_8);
}

尝试使用bufferFileWriter。附加,它对我有用。

FileWriter fileWriter;
try {
    fileWriter = new FileWriter(file,true);
    BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
    bufferFileWriter.append(obj.toJSONString());
    bufferFileWriter.newLine();
    bufferFileWriter.close();
} catch (IOException ex) {
    Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}

我只是补充了一个小细节:

    new FileWriter("outfilename", true)

2.nd parameter (true) is a feature (or, interface) called appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content

换句话说,您可以向gzip文件或http进程添加一些内容

如果我们使用Java 7及以上版本,并且也知道要添加(追加)到文件的内容,我们可以使用NIO包中的newBufferedWriter方法。

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这里有几点需要注意:

指定字符集编码总是一个好习惯,为此我们在StandardCharsets类中有常量。 代码使用try-with-resource语句,其中资源在try之后自动关闭。

虽然OP没有要求,但以防我们想要搜索具有特定关键字的行,例如confidential,我们可以在Java中使用流api:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}

你可以使用下面的代码在文件中追加内容:

 String fileName="/home/shriram/Desktop/Images/"+"test.txt";
  FileWriter fw=new FileWriter(fileName,true);    
  fw.write("here will be you content to insert or append in file");    
  fw.close(); 
  FileWriter fw1=new FileWriter(fileName,true);    
 fw1.write("another content will be here to be append in the same file");    
 fw1.close();