搜索目录指定文件并存储指定类型文件类型

    public static void method_3() {
        File dir=new File("F:\\网络教材");
        FilenameFilter filter=new FilenameFilter(){
            @Override
            public boolean accept(File dir, String name) {
                // TODO Auto-generated method stub
                return name.endsWith(".pdf");
            }    
        };
        List<File> list=new ArrayList<File>();
        listAll(dir,filter,list);
        //writer2File(list,new File("a.txt"));
    }
    public static void listAll(File dir,FilenameFilter filter,List<File> list) {
        File[] files=dir.listFiles();
       for(File file:files)
       {
           if(file.isDirectory())
           {
               listAll(file,filter,list);
           }
           else{
               if(filter.accept(dir,file.getName())){
                   list.add(file);
               }
           }
       }
    }
    private static void writer2File(List<File> list,File destFile) {
        BufferedWriter bufw=null;
        try{
            bufw=new BufferedWriter(new FileWriter(destFile));
            for(File file:list){
                bufw.write(file.getAbsolutePath());
                bufw.newLine();
                bufw.flush();
            }
                
        }catch(IOException e){
            throw new RuntimeException("写入失败");
        }
        finally{
            if(bufw!=null){
                try {
                    bufw.close();
                } catch (IOException e) {
                    
                    throw new RuntimeException("关闭失败");
                }
            }
        }
        
    }

posted on 2012-10-20 17:41  蝌蚪的精神  阅读(190)  评论(0编辑  收藏  举报

导航