關(guān)閉流的方法

一、自己寫一個工具類關(guān)閉

可變參數(shù):...三個點,只能放在形參的最后一個位置。表示可以傳遞任意個參數(shù),處理方式同數(shù)組。
程序

public static void close(Closeable... io) {
        for (Closeable temp : io) {
            if (temp != null) {
                try {
                    temp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static <T extends Closeable> void closeAll(T... io) {

        for (Closeable temp : io) {
            if (temp != null) {
                try {
                    temp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

<br />
二、1.7新增方法,try-with-resource
程序

public static void read(String srcPath) {

        File src = new File(srcPath);
        try (
                ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(src)));
            ) 
            {
                Object o1 = ois.readObject();
                Object o2 = ois.readObject();
                if (o1 instanceof Employee) {
                    Employee e1 = (Employee) o1;
                    System.out.println(e1.getSalary());
                    System.out.println(e1.getName());
                }
                if (o2 instanceof Employee) {
                    Employee e2 = (Employee) o2;
                    System.out.println(e2.getSalary());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
        }

    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 前言 把《C++ Primer》[https://book.douban.com/subject/25708312...
    尤汐Yogy閱讀 9,655評論 1 51
  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的...
    笨鳥慢飛閱讀 6,217評論 0 4
  • 前段時間有位和我一起學(xué)習(xí)的同學(xué)問我“如何學(xué)習(xí)搞定一門課程?”我在想我們一直在討論學(xué)習(xí)、學(xué)習(xí)知識、學(xué)習(xí)技能、學(xué)習(xí)使用...
    李鑫原創(chuàng)閱讀 395評論 2 6
  • 3月3日是我的陰歷生日,那兩天因為忙著為進(jìn)修校來聽課做準(zhǔn)備,早把生日的事忘到了腦后。 中午下班,坐在校車上,翻了一...
    墨香悠然666閱讀 481評論 5 5

友情鏈接更多精彩內(nèi)容