不用寫一大堆finally來關閉資源,所有實現Closeable的類聲明都可以寫在裏面,最常見於流操作,socket操作,新版的httpclient也可以;
需要注意的是,try()的括號中可以寫多行聲明,每個聲明的變量類型都必須是Closeable的子類,用分號隔開
try ( ZipOutputStream out=new ZipOutputStream(new FileOutputStream(s)); ){ out.putNextEntry(new ZipEntry("1239000.txt")); Files.copy(Paths.get(fileStr),out); }catch (Exception e){ e.printStackTrace(); }