向文件中写入数据
用FileWriter实现
1.抛出异常
/*
*创建写入方法,其中path代表要写入的文件地址,str表示要写入的内容
*/
public static void writeToFile(String path, String str) throws IOException {
// 创建FileWrite对象,其中第二个参数设置成false就是覆盖写入,true就是增量存储。
FileWriter fout = new FileWriter(path, true);
//TODO: 将str写入文件
fout.write(str);
fout.close();
System.out.println("已经完成写入!");
}
2.捕捉处理异常
//path:写入路径
public static void write(String path){
FileWriter fw = null;
//捕捉异常
try {
fw = new FileWriter(path);
} catch (IOException e) {
// 打印异常信息
e.printStackTrace();
}finally {
try {
fw.write("sdsdsdsdsdsd");
fw.close();
System.out.println("写完了。");
} catch (IOException e) {
// 打印异常信息
e.printStackTrace();
}
}
}