Is this a safe way to release resources in Java?

Usually, when the code needs some resource that needs to be released, I see how this is done:

InputStream in = null;
try{
    in = new FileInputStream("myfile.txt");
    doSomethingWithStream(in);
}finally{
    if(in != null){
        in.close();
    }
}

What I do not like is that you must initialize the variable to zero and after that set it to a different value, and in the finally block check whether the resource has been initialized by checking whether it is zero. If it is not null, it must be freed. I know that I am bullying, but I feel that it can be done cleaner.

What I would like to do is:

InputStream in = new FileInputStream("myfile.txt");
try{
    doSomethingWithStream(in);
}finally{
    in.close();
}

, . , , ( ), try. , , - - ( Java), ?

:

Inputstream in = new FileInputStream("myfile.txt");
in.close();

, try-finally ?

Edit:

, , . . , - -, , , doSomethingWithStream . . , , . , ( Thread.stop), , , , .

+1
3

, . , Thread.stop() Thread.stop(Throwable) , (ThreadDeath ), .

...

+1

- .

try-finally , , doSomethingWithStream . , , - , finally.

+2

See the Lombok Project . It has an @Cleanup annotation that adjusts to local variables that automatically generate code at compile time to clear the resource.

 import lombok.Cleanup;
 import java.io.*;

 public class CleanupExample {
   public static void main(String[] args) throws IOException {
     @Cleanup InputStream in = new FileInputStream(args[0]);
     @Cleanup OutputStream out = new FileOutputStream(args[1]);
     byte[] b = new byte[10000];
     while (true) {
       int r = in.read(b);
       if (r == -1) break;
       out.write(b, 0, r);
     }
   }
 }
0
source

All Articles