Java io ugly try-finally block

前端 未结 12 1085
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 05:57

Is there a not so ugly way of treat the close() exception to close both streams then:

    InputStream in = new FileInputStream(inputFileName);
          


        
12条回答
  •  温柔的废话
    2020-11-28 06:53

    Here is my answer hopefully much better

    https://stackoverflow.com/a/35623998/2585433

    try {
        fos = new FileOutputStream(new File("..."));
        bos = new BufferedOutputStream(fos);
        oos = new ObjectOutputStream(bos);
    }
    catch (Exception e) {
    }
    finally {
        Stream.close(oos,bos,fos);
    }
    
    
    class Stream {
    
    public static void close(AutoCloseable... array) {
        for (AutoCloseable c : array) {
            try {c.close();}
            catch (IOException e) {}
            catch (Exception e) {}
        }
      } 
    }
    

提交回复
热议问题