java流关闭改进
2016-10-19 00:00
253 查看
摘要: 简化流关闭时null判断和异常捕捉简化开发
流关闭改进之前:
改进之后:
附上代码:
流关闭改进之前:
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) { } } } } } }
相关文章推荐
- 2004-09-02技术分析报告-Cookie关闭及Java Servlet Session处理探讨
- JML起步---使用JML 改进你的Java程序(1)
- [java] 拦截Ctrl+C和系统关闭信号
- Java源码分析:深入探讨Iterator模式及Java 5.0中改进的for循环
- 优化 Java 垃圾收集器改进系统性能
- 优化 Java 垃圾收集器改进系统性
- 改进JAVA字符串分解的方法
- 关于java窗口关闭的疑问
- 优化 Java 垃圾收集器改进系统性能
- JML起步---使用JML 改进你的Java程序(2)
- 改进Java中的对象管理方式,提高程序性能
- 改进JAVA字符串分解的方法
- 改进JAVA字符串分解的方法
- 深层次树状结构遍历的改进 查找硬盘中的 “java.exe”
- JML起步---使用JML 改进你的Java程序(3)
- java窗体运行时最大化及关闭方法示例
- 改进JAVA字符串分解的方法
- 改进JAVA字符串分解的方法
- 优化 Java 垃圾收集器改进系统性能
- Java application 关闭窗口的方法