When does a stream close if its not closed manually?

后端 未结 6 2039
一个人的身影
一个人的身影 2021-01-04 10:27

I would like to know when does a stream close if its not closed manually. By this I mean, will the stream be closed if the scope of its reference is no more?

Conside

6条回答
  •  情话喂你
    2021-01-04 11:07

    With Java 7, you can create one or more “resources” in the try statement. A “resources” is something that implements the java.lang.AutoCloseable interface. This resource would be automatically closed and the end of the try block.

    you can look this and java doc for more info

    private static void printFileJava7() throws IOException {
    
        try(FileInputStream input = new FileInputStream("file.txt")) {
    
            int data = input.read();
            while(data != -1){
                System.out.print((char) data);
                data = input.read();
            }
        }
    }
    

    When the try block finishes the FileInputStream will be closed automatically. This is possible because FileInputStream implements the Java interface java.lang.AutoCloseable. All classes implementing this interface can be used inside the try-with-resources construct.

提交回复
热议问题