forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchFileVisitor.java
More file actions
70 lines (52 loc) · 1.88 KB
/
Copy pathSearchFileVisitor.java
File metadata and controls
70 lines (52 loc) · 1.88 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
package modern.challenge;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
public class SearchFileVisitor implements FileVisitor {
private final Path fileNameToSearch;
private boolean fileFound;
public SearchFileVisitor(Path fileNameToSearch) {
this.fileNameToSearch = Objects.requireNonNull(fileNameToSearch,
"The file to search cannot be null");
}
@Override
public FileVisitResult postVisitDirectory(Object dir, IOException ioe) throws IOException {
if(ioe != null) {
throw ioe;
}
System.out.println("Visited: " + (Path) dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
fileFound = search((Path) file);
if (!fileFound) {
return FileVisitResult.CONTINUE;
} else {
return FileVisitResult.TERMINATE;
}
}
@Override
public FileVisitResult visitFileFailed(Object file, IOException ioe) throws IOException {
return FileVisitResult.CONTINUE;
}
public boolean isFileFound() {
return fileFound;
}
private boolean search(Path file) throws IOException {
Path fileName = file.getFileName();
if (fileNameToSearch.equals(fileName)) {
System.out.println("Searched file was found: "
+ fileNameToSearch + " in " + file.toRealPath().toString());
return true;
}
return false;
}
}