2015-11-11 20:20:04 -08:00
|
|
|
// onjava/ProcessFiles.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-11-11 20:20:04 -08:00
|
|
|
package onjava;
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.io.*;
|
2015-12-06 11:45:16 -08:00
|
|
|
import java.nio.file.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
public class ProcessFiles {
|
|
|
|
public interface Strategy {
|
|
|
|
void process(File file);
|
|
|
|
}
|
|
|
|
private Strategy strategy;
|
|
|
|
private String ext;
|
|
|
|
public ProcessFiles(Strategy strategy, String ext) {
|
|
|
|
this.strategy = strategy;
|
|
|
|
this.ext = ext;
|
|
|
|
}
|
|
|
|
public void start(String[] args) {
|
|
|
|
try {
|
|
|
|
if(args.length == 0)
|
|
|
|
processDirectoryTree(new File("."));
|
|
|
|
else
|
|
|
|
for(String arg : args) {
|
|
|
|
File fileArg = new File(arg);
|
|
|
|
if(fileArg.isDirectory())
|
|
|
|
processDirectoryTree(fileArg);
|
|
|
|
else {
|
|
|
|
// Allow user to leave off extension:
|
|
|
|
if(!arg.endsWith("." + ext))
|
|
|
|
arg += "." + ext;
|
|
|
|
strategy.process(
|
|
|
|
new File(arg).getCanonicalFile());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch(IOException e) {
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
public void
|
|
|
|
processDirectoryTree(File root) throws IOException {
|
2015-12-06 11:45:16 -08:00
|
|
|
PathMatcher matcher = FileSystems.getDefault()
|
|
|
|
.getPathMatcher("glob:**/*.{" + ext + "}");
|
|
|
|
Files.walk(root.toPath())
|
|
|
|
.filter(matcher::matches)
|
|
|
|
.forEach(p -> strategy.process(p.toFile()));
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|