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 }