删除目标目录中的所有zip文件,并仅保留最新的两个zip文件

时间:2013-09-13 13:44:19

标签: java file

我开发了一个将文件从源目录移动到目标目录的应用程序 通过使用apache Fileutils类方法如下所示。

private void filemove(String FilePath2, String s2) { 

        String filetomove = FilePath2 + s2;    //file to move its complete path
        File f = new File(filetomove);
        File d = new File(targetFilePath); //    path of target directory 
        try {
            FileUtils.copyFileToDirectory(f, d);
            f.delete(); //from source dirrectory we are deleting the file if it succesfully move
        //*********** code need to add to delete the zip files of target directory and only keeping the latest two zip files  ************//        
        } catch (IOException e) {
            String errorMessage =  e.getMessage();
            logger.error(errorMessage);

        }

    }

现在当我将文件移动到目标目录时,所以在这种情况下,目标目录将具有某些zip文件,现在目标目录中的这些zip文件正由某些其他作业创建,该作业运行一些进程来创建zip文件,但任何我正在尝试的是,当我将我的文件移动到目标目录,所以在保持目标目录之前,它应检查目标目录,并应删除zip文件,同时应确保只有两个最新的zip文件它不应该删除所以最后目标目录应该有我正在移动的文件和最新的两个zip文件请告知如何实现这一点。

所以请告知登录当它将文件移动到目标目录时,它应该删除目标目录的所有zip文件,仅保留最近的两个zip文件

伙计们请告知

2 个答案:

答案 0 :(得分:0)

不是优化的,但您可以使用。

    String[] extensions = {"zip","rar"};
    Collection<File> fileList = listFiles(FilePath2,extensions,false);
    File[] fileArray = new File[fileList.size()];

    int x = 0;
    for (Iterator iterator = fileList.iterator(); iterator.hasNext();) {
        fileArray[x] = (File) iterator.next();
        x++;
    }

    File temp;

    for(int i=1; i< fileArray.length ; i++) {

        for(int j=0; j<fileArray.length-1; j++) {
            if(fileArray[j].lastModified() > fileArray[j+1].lastModified()) {
                 temp = fileArray [j];
                 fileArray [j] = fileArray [j+1];
                 fileArray [j+1] = temp;
            }
        }
    }

    for(int i=0; i< fileArray.length-2 ; i++) {
        deleteQuietly(fileArray[i]);
    }

答案 1 :(得分:0)

获取数组中的所有文件,然后对它们进行排序,然后忽略前两个:

Comparator<File> fileDateComparator = new Comparator<File>() {
    @Override
    public int compare(File o1, File o2) {
        if(null == o1 || null == o2){
            return 0;
        }
        return (int) (o2.lastModified() - o1.lastModified());//yes, casting to an int. I'm assuming the difference will be small enough to fit.
    }
};

File f = new File("/tmp");
if (f.isDirectory()) {
    final File[] files = f.listFiles();
    List<File> fileList = Arrays.asList(files);
    Collections.sort(fileList, fileDateComparator);
    System.out.println(fileList);
}
相关问题