Java2024/src/chapter7/Example09.java
2024-12-11 14:09:38 +08:00

29 lines
974 B
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package chapter7;
import java.io.FileWriter;
import java.io.IOException;
public class Example09 {
public static void main(String[] args) {
FileWriter writer = null; // 在try外声明以便finally中可以访问
try {
writer = new FileWriter("note.txt");
writer.write("这是第一行\n");
writer.write("这是第二行\n");
System.out.println("文件写入成功!");
} catch (IOException e) {
System.out.println("写入文件出错:" + e.getMessage());
} finally {
// 在finally中确保关闭资源
if (writer != null) { // 防止writer未初始化就抛出异常
try {
writer.close(); // close()方法也可能抛出IOException
} catch (IOException e) {
System.out.println("关闭文件出错:" + e.getMessage());
}
}
}
}
}