Java 7 新的 try-with-resources 语句,自动资源释放

阅读更多

 

 

http://blog.csdn.net/lzm1340458776/article/details/37872095

java

 

private static void customBufferStreamCopyJDK7(File source, File target) {
		//try()-()写需要释放的资源,数据流会在 try 执行完毕后自动被关闭,
		//前提是,这些可关闭的资源必须实现 java.lang.AutoCloseable 接口
		try (InputStream fis = new FileInputStream(source);
				OutputStream fos = new FileOutputStream(target)){

			byte[] buf = new byte[8192];

			int i;
			while ((i = fis.read(buf)) != -1) {
				fos.write(buf, 0, i);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	//
	private static void customBufferStreamCopyOldJDK(File source, File target) {
	    InputStream fis = null;
	    OutputStream fos = null;
	    try {
	        fis = new FileInputStream(source);
	        fos = new FileOutputStream(target);
	 
	        byte[] buf = new byte[8192];
	 
	        int i;
	        while ((i = fis.read(buf)) != -1) {
	            fos.write(buf, 0, i);
	        }
	    }
	    catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	        close(fis);
	        close(fos);
	    }
	}
	 
	private static void close(Closeable closable) {
	    if (closable != null) {
	        try {
	            closable.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	}

 

你可能感兴趣的:(Java 7 新的 try-with-resources 语句,自动资源释放)