preface

In development, we often need to close some resources at the end. For example, read/write file streams, etc., we usually close the resource in finally. But this is not a neat way to write it. Try-with-resources was introduced in JDK1.7 to close resources, so let’s take a look at the simplicity of try-with-resources.

Original statement

This article was first published under the headline “Happyjava”. Happy nuggets address: juejin.cn/user/398428… , Happy’s personal blog :(blog.happyjava.cn)[blog.happyjava.cn] Welcome to reprint, but keep this statement.

Some examples of older versions closing resources

In the old version (and many programmers still do), resources were closed ina finally block, like this:

@Test
public void test4(a) {
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream("D:\\head.jpg");
        // do something
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(inputStream ! =null) {
            try {
                inputStream.close();
            } catch(IOException e) { e.printStackTrace(); }}}}Copy the code

The trouble with this approach is that we need to close the resource ina finally block, so inputStream can only be defined outside the try block. Before closing, one more step is required to nullify inputStream to avoid null pointer exceptions if inputStream is null. This is a very cumbersome way to write it.

try-with-resources

The same try-with-resources feature would make the code much cleaner:

@Test
public void test5(a) {
    try (InputStream inputStream = new FileInputStream("D:\\head.jpg")) {
        byte[] bytes = inputStream.readAllBytes();
        // do something
    } catch(IOException e) { e.printStackTrace(); }}Copy the code

The use of try-with-resources is to enclose the resources to be closed in parentheses after the try keyword. Resources are automatically freed after the try block completes execution.

What resources can be automatically closed by try-with-resources

Not all resources can be closed automatically by try-with-resources. Only classes that implement the java.lang.AutoCloseable interface can be closed automatically. If no class implementing Java.lang.AutoCloseable is defined inside the parentheses of the try, the compiler will report an error.

For example, if you define a class MyResource within parentheses, an error will be reported: java.lang.AutoCloseable class is required.

Custom classes that can be automatically closed

We can also write our own classes that can be automatically closed by try-with-resources by implementing the java.lang.AutoCloseable interface.

class MyResource implements java.lang.AutoCloseable {

    @Override
    public void close(a) {
        System.out.println("Called the close method."); }}Copy the code
@Test
public void test5(a) {
    try (InputStream inputStream = new FileInputStream("D:\\head.jpg");
         MyResource myResource = new MyResource()) {
        byte[] bytes = inputStream.readAllBytes();
        // do something
    } catch(IOException e) { e.printStackTrace(); }}Copy the code

After execution, it prints “Close method called.”

conclusion

Try-with-resources can make code cleaner and less error-prone. Try-with-resources has more advantages than the traditional try-catch-finally method. At least there is no null pointer problem when finally closed resources are not nulled.