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){
            }
        }
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM