Java實現將指定檔案夾內的指定類型的檔案歸類,java歸類

來源:互聯網
上載者:User

Java實現將指定檔案夾內的指定類型的檔案歸類,java歸類

這兩天在學Java IO流,正好讓我產生了將自己的電子書歸類的打算,說做就做,Why not?看著自己所學所用能解決生活中的實際問題,是不是很有成就感,那是必須的!

package DepthSearch;import java.util.*;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FilenameFilter;import java.io.IOException;public class DepthTraverse {public static void main(String[] args) {// TODO Auto-generated method stubFile dirFile=new File("G:/eBook/");FilenameFilter filter=new FilenameFilter() {@Overridepublic boolean accept(File dir, String name) {// TODO Auto-generated method stubreturn name.endsWith(".mobi");}};List<File>list=new ArrayList<File>();try {getFile(dirFile, filter, list);//尋找合格檔案WriteToFile(list);//將尋找到的指定格式的檔案放入指定的目錄中} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void getFile(File dir,FilenameFilter filter,List<File>list)throws IOException{File[]files=dir.listFiles();for(File file:files){if(file.isDirectory())//是目錄則遞迴查詢getFile(file, filter, list);else {if(filter.accept(dir, file.getName()))//是檔案則將檔案放入list列表中list.add(file);}}}public static void WriteToFile(List<File>list) throws IOException{String dirString="G:/eBooks/mobi";//將尋找到的.mobi格式檔案存放於此FileInputStream fis=null;FileOutputStream fos=null;int num=0;byte[]bt=new byte[1024];try {for(File file:list){fis=new FileInputStream(file);//讀檔案fos=new FileOutputStream(new File(dirString,file.getName()));//寫檔案System.out.println(file.getAbsolutePath());while((num=fis.read(bt))!=-1){fos.write(bt, 0, num);fos.flush();}}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{fis.close();fos.close();}}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.