2017-08-01 1 views

答えて

1

私はあなたの質問を完全に理解しているかどうかはわかりませんが、ここでは、ルート・パスからすべてのファイルを再帰的に見つけ出し、それ以外のファイルを削除するSpring Bootアプリケーションのスケジュール・タスクの例を示します過去50日間に修正されました。

このタスクは10秒ごとに実行されます。

@Service 
public class FileService { 

    @Scheduled(fixedDelay = 10000) 
    public void deleteFilesScheduledTask() throws IOException { 
     findFiles("C:/testing"); 
    } 

    public void findFiles(String filePath) throws IOException { 
     List<File> files = Files.list(Paths.get(filePath)) 
           .map(path -> path.toFile()) 
           .collect(Collectors.toList()); 
     for(File file: files) { 
      if(file.isDirectory()) { 
       findFiles(file.getAbsolutePath()); 
      } else if(isFileOld(file)){ 
       deleteFile(file); 
      } 
     } 

    } 

    public void deleteFile(File file) { 
     file.delete(); 
    } 

    public boolean isFileOld(File file) { 
     LocalDate fileDate = Instant.ofEpochMilli(file.lastModified()).atZone(ZoneId.systemDefault()).toLocalDate(); 
     LocalDate oldDate = LocalDate.now().minusDays(50); 
     return fileDate.isBefore(oldDate); 
    } 
} 

この機能を自分のアプリでどのように実装できるかを知っていただければと思います。

+0

私はファイルを削除するための以下のコードを持っていますが、ファイルは削除した後、ネストされたフォルダを削除する必要があります。また、パフォーマンスが向上するように、並列/マルチスレッド処理のためにタスクスレッドプールを使用する必要があるかどうかを知る必要があります。 – Tab

+0

ずつfiles.list(パス) .filter(N - >(getLastModifiedTimeUnchecked(N)> = から&& getLastModifiedTimeUnchecked(N)<=)まで) .forEach(N - > { のSystem.out.println(N) ; 削除(n、(t、u) - > System.err.format( "%s%nを削除できませんでした"、t、u.getMessage())); }); – Tab

+0

public static long getLastModifiedTimeUnchecked(パスパス) throws UncheckedIOException { { long lastTime = Files.getLastModifiedTime(path).toMillis(); return lastTime; } catch(IOException ex){ throw new UncheckedIOException(ex); }} パブリック静的ボイド削除(パス経路、BiConsumer <パス、例外> E){ 試み{ Files.delete(パス)。 } catch(IOException ex){ e.accept(path、ex); } } – Tab

関連する問題