流关闭改进之前:
public void method() { ByteArrayOutputStream bos = null; ObjectOutputStream oos = null; try { bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); ..... } catch (IOException e) { LogUtil.warn(e); } finally { if(bos!=null) { try{ bos.flush(); bos.close(); }catch(IOException e){ } } if(oos!=null) { try{ oos.flush(); oos.close(); }catch(IOException e){ } } } }
改进之后:
public void method() { ByteArrayOutputStream bos = null; ObjectOutputStream oos = null; try { bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); ........... } catch (IOException e) { LogUtil.warn(e); } finally { StreamUtil.flushAndClose(bos, oos); } return null; }
附上代码:
public class StreamUtil { private static final Logger logger = LoggerFactory.getLogger(StreamUtil.class); public static void close(InputStream... is) { if (is != null && is.length > 0) { for (InputStream inputStream : is) { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } } public static void flushAndClose(OutputStream... os) { if (os != null && os.length > 0) { for (OutputStream outputStream : os) { if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { } } } } } public static void flushAndClose(Writer... ws) { if (ws != null && ws.length > 0) { for (Writer writer : ws) { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } public static void close(Reader... rs) { if (rs != null && rs.length > 0) { for (Reader reader : rs) { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } } public static void close(Connection... cs) { if (cs != null && cs.length > 0) { for (Connection c : cs) { if (c != null) { try { c.close(); } catch (SQLException e) { } } } } }}