Project Lombok @Cleanup Annotation

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:

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:

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:

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")); } }