文章目录
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
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
IO
字节流:
InputStream,OutputStream
字符流:
Reader,Writer
IO所有操作都有IOException
*/
import java.io.*;
class FileWriterDemo{
public static void main(String [] args){
//定义在外面,否则finally 中的fw 找不到
FileWriter fw = null;
try{
//创建文件,若文件已存在,会干掉
fw = new FileWriter("FileWriterDemo.txt");
//创建文件,若文件已存在,末尾追加内容
//fw = new FileWriter("FileWriterDemo.txt",true);
fw.write("aabc");
}catch(IOException e){
System.out.println(e.toString());
}finally{
try{
if(null != fw){
fw.close();
/*
关闭资源一定要执行,放在finally中(外层);
关闭操作有IOException:故 try{}catch{}
创建文件就抛出异常,fw==null ;故需判断
*/
}
}catch(IOException e){
System.out.println(e.toString());
}
}
}
}
文章目录