请教:Java关闭文件输出流的问题

import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    //1)如果在方法名处抛出异常,则不能捕获异常
    public static void main(String[] args) { 
        String filename = "C:\\Users\\zxb\\Desktop\\测试目录\\测试文件.txt";
        String str = "中国人民";
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream(filename, true);
            fos.write(str.getBytes());
            //fos.close(); //2)写这里如果在 write 过程中出错,资源可能不会被释放
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fos.close(); //3)写这里代码会报错,因为没有处理异常
        }
    }
}

现在问题是 close 方法放在哪里合适?三个地方均不能满足需要

一般放finally里

finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

 

try关,finally中抛异常啊

也可以这样写

https://www.cnblogs.com/heqiyoujing/p/10759451.html