java try finally block to close stream

前端 未结 8 859
时光取名叫无心
时光取名叫无心 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 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 close(Closeable... closeables) {
    
      HashMap exceptions = null;
    
      for (Closeable closeable : closeables) {
        try {
          if(closeable != null) closeable.close();
        } catch (Exception e) {
            if (exceptions == null) {
              exceptions = new HashMap();
            }
            exceptions.put(closeable, e);
          }
        }
    
        return exceptions;
      }
    }
    

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

提交回复
热议问题