zoukankan      html  css  js  c++  java
  • Java删除过期文件

     1   public static void main(String[] args) throws IOException {
     2         long cut = LocalDateTime.now().minusWeeks(1).toEpochSecond(ZoneOffset.UTC);
     3         Path path = Paths.get("D:\test\");
     4         Files.list(path).filter(n -> getLastModifiedTimeUnchecked(n).to(TimeUnit.SECONDS) < cut)
     5                 .forEach(n -> {
     6                     System.out.println(n);
     7                     delete(n, (t, u) -> System.err.format("Couldn't delete %s%n", t, u.getMessage())
     8                     );
     9                 });
    10     }
    11 
    12 
    13         public static FileTime getLastModifiedTimeUnchecked(Path path, LinkOption... options) throws UncheckedIOException {
    14             try {
    15                 return Files.getLastModifiedTime(path, options);
    16             } catch (IOException ex) {
    17                 throw new UncheckedIOException(ex);
    18             }
    19         }
    20 
    21         public static void delete(Path path, BiConsumer<Path, Exception> e) {
    22             try {
    23                 System.out.println(path);
    24                 Files.delete(path);
    25             } catch (IOException ex) {
    26                 e.accept(path, ex);
    27             }
    28         }
    29 
    30 
    31         public void deleteOldFile(){
    32             long cut = LocalDateTime.now().minusDays(3L).toEpochSecond(ZoneOffset.UTC);
    33             Path path = Paths.get("/path/to/delete");
    34             try {
    35                 Files.list(path)
    36                         .filter(n -> {
    37                             try {
    38                                 return Files.getLastModifiedTime(n).to(TimeUnit.SECONDS) < cut;
    39                             } catch (IOException ex) {
    40                                 //handle exception
    41                                 return false;
    42                             }
    43                         })
    44                         .forEach(n -> {
    45                             try {
    46                                 Files.delete(n);
    47                             } catch (IOException ex) {
    48                                 //handle exception
    49                             }
    50                         });
    51             } catch (IOException e) {
    52                 e.printStackTrace();
    53             }
    54         }
  • 相关阅读:
    Git在eclipse中的使用
    Git协同开发产生的版本冲突
    git&github-远程库的拉取
    【题解】p6160 [Cnoi2020]向量
    【题解】p2388 阶乘之乘
    友情链接
    O(1)求解自然数异或和
    【题解】uva1104 chips challenge
    【题解】p1809 过河问题
    多步操作产生错误,请检查每一步的状态
  • 原文地址:https://www.cnblogs.com/award/p/10834216.html
Copyright © 2011-2022 走看看