java try finally block to close stream

前端 未结 8 852
时光取名叫无心
时光取名叫无心 2020-12-05 17:25

I want to close my stream in the finally block, but it throws an IOException so it seems like I have to nest another try block in my finally<

相关标签:
8条回答
  • 2020-12-05 17:55

    First thing I noticed in your code is curly bracket { } missing from your code if you look at it. also you need to initialize value of r to null so you need to pass null value to object at first so that if condition you have written can do not null condition check and lets you close the stream.

    0 讨论(0)
  • 2020-12-05 18:08

    Like the answer mentioning the Commons IO library, the Google Guava Libraries has a similar helper method for things which are java.io.Closeable. The class is com.google.common.io.Closeables. The function you are looking for is similarly named as Commons IO: closeQuietly().

    Or you could roll your own to close a bunch like this: Closeables.close(closeable1, closeable2, closeable3, ...) :

    import java.io.Closeable;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Closeables {
      public Map<Closeable, Exception> close(Closeable... closeables) {
    
      HashMap<Closeable, Exception> exceptions = null;
    
      for (Closeable closeable : closeables) {
        try {
          if(closeable != null) closeable.close();
        } catch (Exception e) {
            if (exceptions == null) {
              exceptions = new HashMap<Closeable, Exception>();
            }
            exceptions.put(closeable, e);
          }
        }
    
        return exceptions;
      }
    }
    

    And that even returns a map of any exceptions that were thrown or null if none were.

    0 讨论(0)
提交回复
热议问题