java面試try-with-resources問題解答
前言:
這個語句的作用是,確保該語句執(zhí)行之后,關閉每一個資源,也就是說它確保了每個資源都在生命周期結束之后被關閉,因此,比如讀寫文件,我們就不需要顯示的調用close()方法
這個語句的大致模板如下:

我們可以看到我們把需要關閉的資源都放到try()這個括號里面去了,之前都是對異常的捕獲,怎么還可以寫資源語句,這就是奇妙之處,注意分號啊,最后一個資源可以不用加分號,中間的都要加分號,并且,對于java7來說,變量的聲明必須放在括號里面。
下面來說一下具體實現原理:
首先在try()里面的類,必須實現了如下這個接口

這個接口也叫自動關閉資源接口.我們想要寫這樣的語句,必須去實現它里面的close()方法

對于這個類,很多類都已經做了默認實現,所以我們沒有必要顯示去山實現這樣一個東西,直接拿來用就可以了,比如:

我們這些常見的文件操作類,都已經做了實現。
這樣的做法有助于我們寫非常復雜的finally塊,話不多說,直接上代碼:
ImageCopy.java
import java.io.*;
public class ImageCopy {
public static void main(String[] args) {
File srcFile = new File("F:\\java課程資料\\王也.png");
File destFile = new File("E:\\717.png");
copyImage(srcFile,destFile);
}
//這個采用一邊讀,一邊寫的思路來做
public static void copyImage(File srcFile, File destFile) {
//這個太繁瑣了,我們把它進行改進
/* FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
byte[] buff = new byte[1024];
int len = 0;
while((len = fis.read(buff)) != -1) {
fos.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}*/
//這里會自動幫我們關閉打開的這些資源
try( FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos)
) {
byte[] buff = new byte[1024];
int len = 0;
while((len = bis.read(buff)) != -1) {
bos.write(buff,0,len);
}
}catch (Exception e) {
e.printStackTrace();
}
}
//采用字符流來讀取文本操作
public static void copyText(File srcFile,File destFile) {
InputStreamReader fr = null;
OutputStreamWriter fw = null;
try {
fr = new InputStreamReader(new FileInputStream(srcFile),"gbk");
// fw = new FileWriter(destFile);
fw = new OutputStreamWriter(new FileOutputStream(destFile),"gbk");
char[] buff = new char[1024];
int len = 0;
while((len = fr.read(buff)) != -1) {
System.out.println("讀取到的長度:" + len);
fw.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}到此這篇關于java面試try-with-resources問題解答的文章就介紹到這了,更多相關java try-with-resources 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot使用Maven打包異常-引入外部jar的問題及解決方案
這篇文章主要介紹了SpringBoot使用Maven打包異常-引入外部jar,需要的朋友可以參考下2020-06-06
springboot接入cachecloud redis示例實踐
這篇文章主要介紹了springboot接入cachecloud redis示例實踐,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10
java中的FileInputStream三種read()函數用法
這篇文章主要介紹了java中的FileInputStream三種read()函數用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
Double.parseDouble()與Double.valueOf()的區(qū)別及說明
這篇文章主要介紹了Double.parseDouble()與Double.valueOf()的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07

