1 package fr.ifremer.tutti.ui.swing.updater;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 import java.io.IOException;
28 import java.nio.file.FileVisitResult;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.SimpleFileVisitor;
32 import java.nio.file.attribute.BasicFileAttributes;
33
34
35
36
37
38
39
40 public class MoveHelper {
41
42
43 public static void move(Path sourceDirectory, Path targetDirectory, boolean dryRun) throws IOException {
44
45 MoveTreeVisitor copyVisitor = new MoveTreeVisitor(sourceDirectory, targetDirectory, dryRun);
46 Files.walkFileTree(sourceDirectory, copyVisitor);
47
48 }
49
50 static class MoveTreeVisitor extends SimpleFileVisitor<Path> {
51
52 final Path sourceDirectory;
53
54 final int sourcePathCount;
55
56 final Path targetDirectory;
57
58 final boolean dryRun;
59
60 MoveTreeVisitor(Path sourceDirectory, Path targetDirectory, boolean dryRun) {
61 this.sourceDirectory = sourceDirectory;
62 this.targetDirectory = targetDirectory;
63 this.dryRun = dryRun;
64 this.sourcePathCount = sourceDirectory.getNameCount();
65 }
66
67 @Override
68 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
69
70 Path target;
71
72 if (sourceDirectory.equals(dir)) {
73
74 target = targetDirectory;
75
76 } else {
77
78 Path sourceRelativize = dir.subpath(sourcePathCount, dir.getNameCount());
79 target = targetDirectory.resolve(sourceRelativize).toAbsolutePath();
80
81 }
82
83 System.out.println(String.format("Create directory: %s", target));
84 if (!dryRun) {
85 Files.createDirectories(target);
86 }
87
88 return FileVisitResult.CONTINUE;
89
90 }
91
92 @Override
93 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
94
95 Path subPath = file.subpath(sourcePathCount, file.getNameCount());
96 Path target = targetDirectory.resolve(subPath).normalize().toAbsolutePath();
97
98 System.out.println(String.format("Copy file from %s to %s", file, target));
99 if (!dryRun) {
100 Files.move(file, target);
101 }
102
103 return FileVisitResult.CONTINUE;
104
105 }
106
107 @Override
108 public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
109
110 System.out.println(String.format("Delete directory: %s", dir));
111 if (!dryRun) {
112 Files.delete(dir);
113 }
114
115 return FileVisitResult.CONTINUE;
116
117 }
118
119 }
120
121 }