java中如何優雅的關閉流

文章最前: 我是Octopus,這個名字來源於我的中文名--章魚;我熱愛編程、熱愛算法、熱愛開源。

這博客是記錄我學習的點點滴滴,如果您對 Python、Java、AI、算法有興趣,可以關注我的動態,一起學習,共同進步。

相關文章:

  1. LeetCode:55. Jump Game(跳遠比賽)
  2. Leetcode:300. Longest Increasing Subsequence(最大增長序列)
  3. LeetCode:560. Subarray Sum Equals K(找出數組中連續子串和等於k)

文章目錄:

1)關閉流使用try-catch-finally

2)  jdk7開始,try-with-resources

3)項目中用法:


關閉流有兩種方法:

1)關閉流使用try-catch-finally

        FileInputStream fis = null;
	    try {
			fis = new FileInputStream(srcFile);
			fis.read(fileContent);
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fis!=null)
			{
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

2) jdk7開始,try-with-resources

增加了對需要關閉的資源管理處理的特殊語法try-with-resourcestry(資源變量=創建資源對象){} catch(){}

其中資源對象需要實現autoCloseable接口,例如:inputStream,outputStream,Connection,statement,Result等接口都實現了AutoCloseable,使用try-with-resources可以不寫finally語句,編譯器會幫助生成關閉資源代碼。

try (FileInputStream fis = new FileInputStream(srcFile)){
			fis.read(fileContent);
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		} 

3)項目中用法:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章