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         }
  • 相关阅读:
    Java反射研究(3)
    Java反射研究(2)
    Java反射研究(1)
    从百度文库中复制文本的方法
    jdk/bin中的native2ascii.exe使用
    EA经典入门教程
    JSP自定义标签(3)
    JSP自定义标签(1)
    将Java doc转换为chm的方法
    多态性——vptr和vtable
  • 原文地址:https://www.cnblogs.com/award/p/10834216.html
Copyright © 2011-2022 走看看