public static printFnames(String sDir) {
Files.find(Paths.get(sDir), 999, (p, bfa) -> bfa.isRegularFile()).forEach(System.out::println);
}
Given something like above, or using Apache IO or Java NIO, how can I recursively look for directory that match the following pattern:
COB03Oct2017 (which resembles last working day basically)
I have a structure like /sourcefolder/clientfolders/COB03Oct2017/file.pdf
There are many clientfolders and many COBddmmyyyy folders.
Let's say I have already got a method that gives me the cob folder name.
How can I find all matching cob folders for all client folders?
@Test
public void testFiles() {
String sourcePath = "C:\\sourcepath\\";
String cobPattern = "COB" + DateHelper.getPreviousWorkingDay();
List<Path> clientDirectories = null;
try {
clientDirectories = Files.find(Paths.get(sourcePath), 1,
(path, bfa) -> bfa.isDirectory())
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
List<Path> cobDirectories = getCobDirectories(clientDirectories, cobPattern);
}
private List<Path> getCobDirectories(List<Path> clientDirectories, String cobPattern) {
List<Path> collect = new ArrayList<>();
clientDirectories
.stream()
.forEach(path -> {
try {
collect.addAll(Files.find(Paths.get(path.toString()), 1,
(p, bfa) -> bfa.isDirectory()
&& p.getFileName().toString().equals(cobPattern)).collect(Collectors.toList()));
} catch (IOException e) {
e.printStackTrace();
}
});
System.out.println("Done");
return collect;
}
The above is my attempt. But with your help, I would like to know if I am doing anything wrong, how it can be written better etc
This bit also worked. But again can this be improved? How do ignore exceptions such AccessDenied
@Test
public void testFiles() {
String sourcePath = "\\\\server\\pathToCustomerReports\\";
String cobPattern = "COB" + DateHelper.getPreviousWorkingDay();
List<Path> clientDirectories = null;
try {
clientDirectories = Files.find(Paths.get(sourcePath), 1,
(path, bfa) -> bfa.isDirectory())
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
List<Path> cobDirectories = new ArrayList<>();
clientDirectories.forEach(path -> cobDirectories.addAll(getCobdirs(path)));
System.out.println("Done");
}
private List<Path> getCobdirs(Path path) {
List<Path> cobDirs = new ArrayList<>();
String cobPattern = "COB" + DateHelper.getPreviousWorkingDay();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path p : stream) {
if (path.toFile().isDirectory() && p.getFileName().toString().equals(cobPattern)) {
cobDirs.add(p);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return cobDirs;
}