try(Resource res=XX ()){
work with res
}
try-with-resource是JDK1.7的新特性,()括號里的內容支持包括流以及任何可關閉的資源,數據流(其他資源)會在try塊執行完畢之后自動被關閉,省去了寫finally塊關閉資源的步驟。
//解壓tar.gz文件
/*
* @param sourceFile要解壓的文件
* @param target 要解壓到的目錄
*/
private void untarFile(File sourceFile,String target) throws IOException{
if(sourceFile.exists() && sourceFile.isFile()){
try(TarArchiveInputStream tarIn=new TarArchiveInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(sourceFile))))){
TarArchiveEntry entry=null;
while((entry=tarIn.getNextTarEntry())!=null) {
File tarFile=new File(target,entry.getName());
if(entry.isDirectory()) {//是目錄,創建目錄
tarFile.mkdirs();
}else {//是文件
if(tarFile.getParentFile().exists()) {//可能存在創建目錄延遲,父目錄還沒創建好,找不着
tarFile.getParentFile().mkdirs();
}
try(OutputStream out=new FileOutputStream(tarFile)){
int length=0;
byte[] b=new byte[2048];
while((length=tarIn.read())!=-1) {
out.write(b,0,length);
}
}catch (Exception e) {
// TODO: handle exception
}
}
}
}catch (Exception e) {
// TODO: handle exception
}
}
}
需要引入的包
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;