原文: https://howtodoinjava.com/java8/java-8-write-to-file-example/
Java 8 示例将内容导入文件。 您可以在链接的博客文章中找到使用 Java 8 API 读取文件的示例。
1. Java 8 使用BufferedWriter写入文件
BufferedWriter用于将文本写入字符或字节流。 在打印字符之前,它将字符存储在缓冲区中并成束打印。 如果不进行缓冲,则每次调用print()方法都会导致将字符转换为字节,然后将这些字节立即写入文件中,这可能会非常低效。
Java 程序使用 Java 8 API 将内容写入文件:
//Get the file referencePath path = Paths.get("c:/output.txt");//Use try-with-resource to get auto-closeable writer instancetry (BufferedWriter writer = Files.newBufferedWriter(path)){writer.write("Hello World !!");}
2. 使用Files.write()写入文件
使用Files.write()方法也是非常干净的代码。
String content = "Hello World !!";Files.write(Paths.get("c:/output.txt"), content.getBytes());
以上两种方法都适用于几乎所有需要用 Java 8 编写文件的用例。
学习愉快!
