Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent to python's "with"

Python has a nice feature: the "with" statement. It's useful for making global changes that affect all code called within the statement.

e.g. you could define a class CapturePrintStatements to capture all print statements called within the "with"

with CapturePrintStatements() as c:
    print 'Stuff Done'
print 'More Stuff Done'
assert c.get_text() == 'Stuff Done'

Is there an equivalent in Java?

like image 952
Peter Avatar asked Jan 31 '16 16:01

Peter


1 Answers

try-with-resources is its Java equivalent, and is available in Java 7 and up.

That gives you the possibility to work with resources that need to be explicitly closed, without worrying about closing them. For the example:

Before Java7:

InputStream input = null;

try {
    input = new FileInputStream("myFile.txt");

} finally {
    if(input != null){
        input.close();
    }
}

Java 7 & up:

try(FileInputStream input = new FileInputStream("myFile.txt")) {
    // Do something with the InputStream
}

This is the try-with-resources construct. When the execution flow will go out of the try block, the FileInputStream will be closed automatically. This is due to the fact that FileInputStream implements the AutoCloseable interface.

like image 55
Mohammed Aouf Zouag Avatar answered Sep 23 '22 10:09

Mohammed Aouf Zouag