原文: https://howtodoinjava.com/java/io/how-to-write-to-file-in-java-bufferedwriter-example/

如果您想使用BufferedWriter将某些内容写入 Java 中的文件中,请使用以下代码作为模板,并按自己的方式重复使用它。

1)使用不带try-with-resourcesBufferedWriter(在 Java 7 之前)

  1. package com.howtodoinjava.examples.io;
  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. public class BufferedWriterExample
  7. {
  8. public static void main(String[] args)
  9. {
  10. try {
  11. String content = "Hello Learner !! Welcome to howtodoinjava.com.";
  12. File file = new File("c:/temp/samplefile.txt");
  13. FileWriter fw = new FileWriter(file);
  14. BufferedWriter bw = new BufferedWriter(fw);
  15. bw.write(content);
  16. bw.close();
  17. }
  18. catch (IOException e)
  19. {
  20. e.printStackTrace();
  21. }
  22. }
  23. }

2)将BufferedWritertry-with-resources结合使用(Java 7 及更高版本)

  1. package com.howtodoinjava.examples.io;
  2. import java.io.BufferedWriter;
  3. import java.io.FileWriter;
  4. import java.io.IOException;
  5. public class BufferedWriterExample
  6. {
  7. public static void main(String[] args)
  8. {
  9. try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\temp\\testOut.txt")))
  10. {
  11. String content = "Hello Learner !! Welcome to howtodoinjava.com.";
  12. bufferedWriter.write(content);
  13. }
  14. catch (IOException e)
  15. {
  16. e.printStackTrace();
  17. }
  18. }
  19. }

祝您学习愉快!