🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Java 8 写入文件示例 > 原文: [https://howtodoinjava.com/java8/java-8-write-to-file-example/](https://howtodoinjava.com/java8/java-8-write-to-file-example/) Java 8 示例将内容导入文件。 您可以在链接的博客文章中找到使用 Java 8 API 读取文件的[示例。](//howtodoinjava.com/java8/read-file-line-by-line-in-java-8-streams-of-lines-example/) ## 1\. Java 8 使用`BufferedWriter`写入文件 [`BufferedWriter`](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html)用于将文本写入字符或字节流。 在打印字符之前,它将字符存储在缓冲区中并成束打印。 如果不进行缓冲,则每次调用`print()`方法都会导致将字符转换为字节,然后将这些字节立即写入文件中,这可能会非常低效。 Java 程序*使用 Java 8* API 将内容写入文件: ```java //Get the file reference Path path = Paths.get("c:/output.txt"); //Use try-with-resource to get auto-closeable writer instance try (BufferedWriter writer = Files.newBufferedWriter(path)) { writer.write("Hello World !!"); } ``` ## 2\. 使用`Files.write()`写入文件 使用[`Files.write()`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-byte:A-java.nio.file.OpenOption...-)方法也是非常干净的代码。 ```java String content = "Hello World !!"; Files.write(Paths.get("c:/output.txt"), content.getBytes()); ``` 以上两种方法都适用于几乎所有需要用 Java 8 编写文件的**用例**。 学习愉快!