forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveFileVisitor.java
More file actions
80 lines (62 loc) · 2.76 KB
/
MoveFileVisitor.java
File metadata and controls
80 lines (62 loc) · 2.76 KB
1
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package modern.challenge;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;
import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Objects;
public class MoveFileVisitor implements FileVisitor {
private final Path moveFrom;
private final Path moveTo;
private static FileTime time;
public MoveFileVisitor(Path moveFrom, Path moveTo) {
this.moveFrom = Objects.requireNonNull(moveFrom, "The location to move from cannot be null");
this.moveTo = Objects.requireNonNull(moveTo, "The location to move to cannot be null");
}
@Override
public FileVisitResult postVisitDirectory(Object dir, IOException ioe) throws IOException {
Path newDir = moveTo.resolve(moveFrom.relativize((Path) dir));
try {
Files.setLastModifiedTime(newDir, time);
Files.delete((Path) dir);
} catch (IOException e) {
System.err.println("Unable to copy all attributes to: " + newDir + " [" + e + "]");
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
System.out.println("Move directory: " + (Path) dir);
Path newDir = moveTo.resolve(moveFrom.relativize((Path) dir));
try {
Files.copy((Path) dir, newDir, REPLACE_EXISTING, COPY_ATTRIBUTES);
time = Files.getLastModifiedTime((Path) dir);
} catch (IOException e) {
System.err.println("Unable to move " + newDir + " [" + e + "]");
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
System.out.println("Move file: " + (Path) file);
try {
moveSubTree((Path) file, moveTo.resolve(moveFrom.relativize((Path) file)));
} catch (IOException e) {
System.err.println("Unable to move " + moveFrom + " [" + e + "]");
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Object file, IOException ioe) throws IOException {
return FileVisitResult.CONTINUE;
}
private static void moveSubTree(Path moveFrom, Path moveTo) throws IOException {
Files.move(moveFrom, moveTo, REPLACE_EXISTING, ATOMIC_MOVE);
}
}