Java使用FileWriter和BufferedWriter添加内容到文件末尾

From: http://beginnersbook.com/2014/01/how-to-append-to-a-file-in-java/


/* 使用FileWriter 和 BufferedWriter将内容追加到文件末尾
 */

import java.io.*;

public class Exercise {
  
  public static void main(String args[]) {
    try {
      String content =
          "This is my content which would be appended " + "at the end of the specified file";
      // Specify the file name and path here
      File file = new File("/home/zjz/Desktop/myFile.txt");
      // This logic is to create the file if the file is not already present
      if (!file.exists()) {
        file.createNewFile();
      }
      // Hrer true is to append the content to the file
      FileWriter fw = new FileWriter(file, true);
      // BufferedWriter writer give better performance
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(content);
      // closing BufferedWriter Stream
      bw.close();
      System.out.println("Data successfully appended at the end of file.");
    } catch (IOException e) {
      System.out.println("Exception occurred:");
      e.printStackTrace();
    }
  }
  
}


你可能感兴趣的:(java)