Java 实例 - 向文件中追加数据

以下实例演示了使用 filewriter 方法向文件中追加数据:

Main.java 文件

  1. import java.io.*;
  2. public class Main {
  3. public static void main(String[] args) throws Exception {
  4. try {
  5. BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
  6. out.write("aString1\n");
  7. out.close();
  8. out = new BufferedWriter(new FileWriter("filename",true));
  9. out.write("aString2");
  10. out.close();
  11. BufferedReader in = new BufferedReader(new FileReader("filename"));
  12. String str;
  13. while ((str = in.readLine()) != null) {
  14. System.out.println(str);
  15. }
  16. in.close();
  17. }
  18. catch (IOException e) {
  19. System.out.println("exception occoured"+ e);
  20. }
  21. }
  22. }

以上代码运行输出结果为:

  1. aString1
  2. aString2