Java使用FileWriter类向文件写入内容

本文最后更新于:3 个月前

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class Main {
//使用FileWriter向文本文件中写信息
public static void main(String[] args) {
String str = "Hello World";
//1.创建流
Writer fw = null;
try {
/*创建txt文件*/
File file = new File("D:\\hello.txt");
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter("D:\\hello.txt");//1
//2.写入信息
fw.write(str);
// 3.刷新缓冲区,即写入内容
fw.flush();
if (fw != null) {
// 4.关闭流,关闭缓冲流时,也会刷新一次缓冲区
fw.close();

}
} catch (IOException e) {
e.printStackTrace();
}
}
}

结果:

image-20221114144244343


Java使用FileWriter类向文件写入内容
https://alec-97.github.io/posts/975683122/
作者
Shuai Zhao
发布于
2022年12月16日
许可协议