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());
                }
            }
        }

    }
}
