Java7技术系列:try-with-resource Java7技术系列:int与二进制的转换优化 Java7技术系列:MultiCatchException Java7技术系列:NIO.2异步IO Java7技术系列:DI依赖注入 Java7技术系列:Queue Java7技术系列:Java并发
/** * Java7以前对IO流的处理除了语法复杂,即使使用了try catch但仍有可能流并没有正常关闭 */ private static void tryCatchBeforeJava7(String targetUrl) { InputStream is = null; OutputStream os = null; try { File file = new File(targetUrl); URL url = new URL(""); is = url.openStream(); os = new FileOutputStream(file); byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) >= 0) { os.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (os != null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 让Java7自己关闭流,能避免认为疏漏或错误 * * try-with-resource能自动关闭实现了AutoCloseable或Closeable接口的资源 * 在执行的语句抛出异常时,流的关闭会根据代码声明流相反的顺序关闭 * * try-with-resource也可以有catch和finally语句,在try-with-resource抛出异常后,会再调用finally语句 */ private static void tryWithResource(String targetUrl) throws MalformedURLException { File file = new File(targetUrl); URL url = new URL(""); try (InputStream is = url.openStream(); OutputStream os = new FileOutputStream(file)) { byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); } } /** * 使用try-with-resource特性时还是要小心,因为在某些情况下资源可能无法关闭。 * 比如下面的代码,如果文件somFile.bin创建ObjectInputStream时出错,FIleInputStream可能就无法正确关闭 * * 为避免该问题,每一个资源都应该独立声明 */ private static void tryWithResourceAttention() { // 创建ObjectInputStream时如果出错,将导致FileInputStream无法正确关闭 try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("someFile.bin"))) { } // 每个资源独立声明,防止某些资源无法正常关闭 try (FileInputStream is = new FileInputStream("someFile.bin"); ObjectInputStream in = new ObjectInputStream(is)) { } }