学习使用 Files.writeString(path,string,options)
方法。此API已在 Java 11 中引入。
java.nio.file.Files
类具有两个重载的 static 静态方法将内容写入文件。
public static Path writeString(Path path, CharSequence csq, OpenOption... options) throws IOException public static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options) throws IOException
writeString(path,string,StandardCharsets.UTF_8,options)
。 options
指定如何打开文件。Java程序,使用 Files.writeString()
方法将String写入文件。
import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.Files; import java.io.IOException; import java.nio.file.StandardOpenOption; public class Main { public static void main(String[] args) { Path filePath = Paths.get("C:/", "temp", "test.txt"); try { //Write content to file Files.writeString(filePath, "Hello World !!", StandardOpenOption.APPEND); //Verify file content String content = Files.readString(filePath); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } } }
程序输出。
链接:https://www.learnfk.comhttps://www.learnfk.com/java/java11-write-string-to-file.html
来源:LearnFk无涯教程网
Hello World !!
文件 c:/temp/test.txt
最初为空。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)