1. 程式人生 > 其它 >Java關閉流的方式

Java關閉流的方式

情景

寫程式碼時發現如果打開了多個stream,那麼關閉的時候需要些很多冗餘程式碼。就像下面這樣:

public static void main(String[] args) {
	File file = new File("D:" + File.separator + "test.txt");
	InputStream in = null;
	try {
		in = new FileInputStream(file);
		// operation input stream
		// ...
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
                // !!!這裡如果要關閉的流很多,那麼就會寫出很多冗餘且相似的程式碼
		if (in != null) {
			try {
				in.close();
			} catch (IOException e) {
				// ignore
			}
		}
	}
}

如果開啟的流超過10個,那麼程式碼中很多都是上面那樣的程式碼。所以,需要編寫方法去統一處理關閉流。

解決

方法1:自行編碼實現

可以把這個方法放到工具類中。但是本著不要重複造輪子的想法, 應該有工具類已經實現了這個方法。


private void close(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

方法2:使用commons-io的IOUtils

Maven座標:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

原始碼:


    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }

呼叫示例:

public static void main(String[] args) {
	File file = new File("D:" + File.separator + "test.txt");
	InputStream in = null;
	try {
		in = new FileInputStream(file);
		// operation input stream
		// ...
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
		IOUtils.closeQuietly(in);
	}
 
}

方法3:try-with-resource (JDK1.7+)

在common-io-2.6版本中,這個IOUtils.closeQuietly(arg0);方法已經被棄用了,並且沒有替代方案。

@Deprecated的說明如下:As of 2.6 removed without replacement. Please use the try-with-resources statement or handle suppressed exceptions manually.給我們的建議就是使用try-with-resources語句或者手動處理壓制的異常。

try-with-resource這個語法糖是JDK1.7開始引入的,具體語法如下:

/**
 * auto closeable stream為實現自動關閉的Stream
 * JDK1.7 新增了一個java.lang.AutoCloseable介面,介面內部只有close()方法。
 * JDK1.7 同時修改了java.io.Closeable介面,這個介面繼承了AutoCloseable介面。
 * 所以之前那些實現Closeable介面的stream都可以實現AutoCloseable介面中的自動關閉的功能。
 */
try (auto closeable stream) {
    
} catch (Exception e) {
}

示例:

public static void main(String[] args) {
	File file = new File("D:" + File.separator + "test.txt");
	try (InputStream in = new FileInputStream(file)) {
		// operation input stream
		// ...
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// ignore
	}
}