java嵌套的文件流如何正确的关闭

1. 嵌套打开的流只需关闭最后打开的流,先打开的会自动关闭;

2. 打开的流可以多次关闭不会出错;

3. 后面尝试打开流时可能会发生异常,此时要考虑关闭前面已经打开的流。

 

下面是一种可行的方法:

public static Object read(String filePath){
        File file = new File(filePath);
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        try{
            fileInputStream = new FileInputStream(file);
            objectInputStream = new ObjectInputStream(fileInputStream);
            Object object = objectInputStream.readObject();
            return object;
        }catch(Exception e){
            return null;
        }finally {
            try{
                if(objectInputStream!=null){
                    objectInputStream.close();
                }
                if(fileInputStream!=null){
                    fileInputStream.close();
                }
            }catch (Exception e2){
            }
        }
    }

  

posted @ 2022-03-14 21:11  bert_qin  阅读(1224)  评论(0编辑  收藏  举报