JavaIO流篩選檔案並輸出到指定資料夾下
阿新 • • 發佈:2018-12-19
今天覆習了File類中的獲取目錄中包含子目錄在內的所有檔名稱
public static void getFile(File file) { File[] files = file.listFiles(); //獲得檔案陣列 for(File file1:files){//遍歷檔案陣列 if(file1.isDirectory())//首先判斷是否是資料夾,假如是,進入遞迴呼叫 { getFile(file1); }else{ System.out.println(file1);//否則輸出,這裡自動呼叫File.toString(),方法 已被重寫 } } System.out.println(file); } public static void delete(File file) { File[] files = file.listFiles(); for(File file1:files){ if(file1.isDirectory()) { delete(file1); }else{ System.out.println(file1.getName()+"已被刪除"); file1.delete(); } } if(file.exists()){//刪除呼叫目錄 file.delete(); System.out.println(file.getName()+"資料夾已被刪除"); } }
結合IO流,進行檔案的篩選和輸出
public static void getDocFile(File file ,List<File> list)//首先進行檔案的篩選 { File[] files = file.listFiles(); for(File file1:files) { if(file1.isDirectory()){ getDocFile(file1, list); }else{ if(file1.getName().endsWith(".doc")){ list.add(file1);//將符合篩選條件的檔案型別假如到檔案陣列中 } } } } public static void outDocFile(List<File> list,String path) throws IOException{ BufferedInputStream buin = null ; BufferedOutputStream buout= null; int i = 0; for(File file:list) { i++; try{ buin = new BufferedInputStream(new FileInputStream(file)); buout= new BufferedOutputStream(new FileOutputStream(new File(path+i+".doc"))); byte[] bit = new byte[1024]; int len = 0; while((len = buin.read(bit))!=-1){ buout.write(bit,0,len); } }catch(IOException e){ System.out.println("失敗"); }finally{ if(buin != null){ try { buin.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }finally{ buin = null; } try { buout.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ buout = null; } } } } }
通過修改篩選條件的字尾名可以該表要獲得的檔案型別