0

以下に示すように、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ファイルを削除する必要があるということです削除するので、最後にターゲットディレクトリに移動中のファイルと最新の2つのzipファイルが必要です。これを達成する方法を教えてください。

そのため、ファイルをターゲット ディレクトリに移動するときに、ターゲット ディレクトリのすべての zip ファイルを削除し、最近の 2 つの zip ファイルのみを保持する必要があることをログインに通知してください。

皆さんアドバイスください

4

2 に答える 2

0

配列内のすべてのファイルを取得して並べ替え、最初の 2 つを無視します。

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);
}
于 2013-09-13T14:49:28.927 に答える