💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Java – `BufferedWriter` > 原文: [https://howtodoinjava.com/java/io/how-to-write-to-file-in-java-bufferedwriter-example/](https://howtodoinjava.com/java/io/how-to-write-to-file-in-java-bufferedwriter-example/) 如果您想使用`BufferedWriter`将某些内容写入 Java 中的文件中,请使用以下代码作为模板,并按自己的方式重复使用它。 ## 1)使用不带`try-with-resources`的`BufferedWriter`(在 Java 7 之前) ```java package com.howtodoinjava.examples.io; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample { public static void main(String[] args) { try { String content = "Hello Learner !! Welcome to howtodoinjava.com."; File file = new File("c:/temp/samplefile.txt"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` ## 2)将`BufferedWriter`与`try-with-resources`结合使用(Java 7 及更高版本) ```java package com.howtodoinjava.examples.io; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample { public static void main(String[] args) { try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\temp\\testOut.txt"))) { String content = "Hello Learner !! Welcome to howtodoinjava.com."; bufferedWriter.write(content); } catch (IOException e) { e.printStackTrace(); } } } ``` **祝您学习愉快!**