Java 7簡化資源清理(try-with-resources)自動關閉資源的try語句
自動關閉資源格式:
try( )//此處多了圓括號,()圓括號內寫打開資源的代碼,在這里創建的對象必須實現Autocloseable接口
{
IO操作
}
catch(){
處理異常的代碼
}
Eg:package july7file;
//java7開始的自動關閉資源
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Demo8 {
public static void main(String[] args) throws IOException {
File src = new File("E:/自薦信.doc");
File tar = new File("E:/自薦信1.doc");
copy(src, tar);
System.out.println("Well done !");
}
public static void copy(File src, File tar) throws IOException {
try (InputStream is = new FileInputStream(src);
OutputStream os = new FileOutputStream(tar);) //圓括號內寫打開資源的操作
{
byte[] b = new byte[1024];
int len;
while ((len = is.read(b)) != -1) {
os.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}