測試try-with-resources 把資源返回後,什麼時候自動關閉資源

public class MyInputStream implements AutoCloseable {
    private static final String io = "666";

    public static String getIo() {
        return io;
    }

    void read(String content) {
        System.out.println("Read content " + content);
    }

    @Override
    public void close() throws Exception {
        System.out.println("Input stream is closed.");
    }

    // 測試把資源返回,什麼時候會自動關閉資源
    public static void main(String[] args) {
        try (MyInputStream ss = test2()) {
            System.out.println("111");
            System.out.println(ss.getIo());
            ss.read("main");
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    public static  MyInputStream test2() {
        try (MyInputStream mis = new MyInputStream()) {
            mis.read("MyInputStream");
            return mis;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

class MyOutputStream implements AutoCloseable {

    void write(String content) {
        System.out.println("write content " + content);
    }

    @Override
    public void close() throws Exception {
        System.out.println("out stream is closed.");
    }

}

 

輸出結果爲:

Read content MyInputStream
Input stream is closed.
111
666
Read content main
Input stream is closed.

資源會被關閉兩次。當然 最好不要將資源直接作爲結果返回。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章