try (BufferedWriter writer =
Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write(“Hello World -创建文件!!”);
}
//追加写模式
try (BufferedWriter writer =
Files.newBufferedWriter(path,
StandardCharsets.UTF_8,
StandardOpenOption.APPEND)){
writer.write(“Hello World -字母哥!!”);
}
}
2. Files.write(Java7)
这种方式是实现文本文件简单读写最方便快捷的方式。
@Test
void testCreateFile2() throws IOException {
String fileName = “D:\data\test\newFile2.txt”;
// 从JDK1.7开始提供的方法
// 使用Files.write创建一个文件并写入
Files.write(Paths.get(fileName),
“Hello World -创建文件!!”.getBytes(StandardCharsets.UTF_8));
// 追加写模式
Files.write(
Paths.get(fileName),
“Hello World -字母哥!!”.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.APPEND);
}
3. PrintWriter
PrintWriter是一个比较古老的文件创建及写入方式,从JDK1.5就已经存在了,比较有特点的是:PrintWriter的println方法,可以实现一行一行的写文件。
@Test
void testCreateFile3() throws IOException {
String fileName = “D:\data\test\newFile3.txt”;
// JSD 1.5开始就已经存在的方法
try (PrintWriter writer = new PrintWriter(fileName, “UTF-8”)) {