Java 7 try-with-resources 語句,自動資源釋放,提高容錯率!

從Java 7 build 105 版本開始,Java 7 的編譯器和運行環境支持新的 try-with-resources 語句,稱爲 ARM 塊(Automatic Resource Management) ,自動資源管理。

新的語句支持包括流以及任何可關閉的資源,例如,一般我們會編寫如下代碼來釋放資源:


private static void testTry(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();
	        }
	    }
	}

代碼挺複雜的,異常的管理很麻煩。

而使用 try-with-resources 語句來簡化代碼如下:

	private static void customBufferStreamCopy(File source, File target) {
	    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();
	    }
	}

代碼清晰很多吧?在這個例子中,數據流會在 try 執行完畢後自動被關閉,前提是,這些可關閉的資源必須實現 java.lang.AutoCloseable 接口。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章