1. 程式人生 > >JAVA中刪除資料夾下及其子資料夾下的某類檔案

JAVA中刪除資料夾下及其子資料夾下的某類檔案

##定時刪除3月以前的圖片
##cron表示式    秒 分 時 天 月 ?
##每月1日整點執行
CRON1=0 0 0 1 * ?
scheduled.enable1=false
##圖片路徑
filePath=E:\\FTP\\FtpS\\Vldata\\Vlbfile\\ 



/**刪除3月前拜訪圖片**/
    @Scheduled(cron="${CRON1}")
    public void delImg(){
        if(Boolean.parseBoolean(scheduled1)){

//        String filePath ="E:\\FTP\\FtpS\\Vldata\\Vlbfile\\";
            String filePath =path;
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -3);//減去三個月
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            long dateNowStr = Long.parseLong(sdf.format(calendar.getTime()));
            int i=0;
//        System.out.println("格式化:"+dateNowStr);
            ArrayList<String> listFileName = new ArrayList<String>();
            getAllFileName(filePath,listFileName);
            for(String name:listFileName){
                name=name.replace(filePath,"");
                String str1 = null;
                if(name.contains("vdvc80100")){

                    String str = name.substring(0,name.indexOf("80100_"));
                    str1 = name.substring(str.length()+6,str.length()+14);
                }
//            if(name.contains("vdvc80100")&&(Integer.valueOf(name.substring(10,18)))<dateNowStr){
                if(name.contains("vdvc80100")&&(Integer.valueOf(str1))<dateNowStr){
                    File f = new File(filePath+name);
//                System.out.println("圖片路徑"+filePath+name);

                    f.delete();
//                System.out.println("刪除檔案成功!"+f.getName());
                }
            }
//        System.out.println("刪除過期拜訪圖片數: "+i);
        }else {

            System.out.println("檔案刪除定時器已關閉!");
        }
    }
    /**
     * 遍歷獲取資料夾下所有檔案
     * @param path
     * @param listFileName
     */
    public static void getAllFileName(String path,ArrayList<String> listFileName){
        File file = new File(path);
        File [] files = file.listFiles();
        String [] names = file.list();
        if(names != null){
            String [] completNames = new String[names.length];
            for(int i=0;i<names.length;i++){
                completNames[i]=path+names[i];
            }
            listFileName.addAll(Arrays.asList(completNames));
        }
        for(File a:files){
            if(a.isDirectory()){//如果資料夾下有子資料夾,獲取子資料夾下的所有檔案全路徑。
                getAllFileName(a.getAbsolutePath()+"\\",listFileName);
            }
        }
    }

&n