When we use a resource like InputStream, OutputStream in Java, we should remember to close that resource after using.
Before Java 7, we can close a resource in a finally block as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.huongdanjava.lombok; import java.io.*; public class Example { public static void main(String[] args) throws IOException { InputStream is = null; try { is = new FileInputStream(new File("/Users/Khanh/text.txt")); } finally { if (is != null) { is.close(); } } } } |
Since Java 7, we can use the try with resource to close the resource automatically as below:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.huongdanjava.lombok; import java.io.*; public class Example { public static void main(String[] args) throws IOException { try (InputStream is = new FileInputStream(new File("/Users/Khanh/text.txt"));) { } } } |
Using try with resource, Java will invoke the method close() of the resource after using automatically.
With Project Lombok, we have another alternative way to close a resource automatically by using @Cleanup annotation:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.huongdanjava.lombok; import lombok.Cleanup; import java.io.*; public class Example { public static void main(String[] args) throws IOException { @Cleanup InputStream is = new FileInputStream(new File("/Users/Khanh/text.txt")); } } |
In this case, if you check the file Example.class in /target/classes/com/huongdanjava/lombok, you will see the content as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.huongdanjava.lombok; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collections; public class Example { public Example() { } public static void main(String[] args) throws IOException { InputStream is = new FileInputStream(new File("/Users/Khanh/text.txt")); if(Collections.singletonList(is).get(0) != null) { is.close(); } } } |
Using @Cleanup annotation, we can also declare the method name of close method in the case the close method of resource is not named close(). Like below:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.huongdanjava.lombok; import lombok.Cleanup; import java.io.*; public class Example { public static void main(String[] args) throws IOException { @Cleanup(value = "close") InputStream is = new FileInputStream(new File("/Users/Khanh/text.txt")); } } |