OnJava8-Examples/onjava/ProcessFiles.java

56 lines
1.6 KiB
Java
Raw Normal View History

// onjava/ProcessFiles.java
2015-12-15 11:47:04 -08:00
// (c)2016 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.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// {ValidateByHand}
2016-07-28 12:48:23 -06:00
// {java onjava.ProcessFiles}
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
}
// Demonstration of how to use it:
public static void main(String[] args) {
new ProcessFiles(file -> System.out.println(file),
"java").start(args);
}
2015-09-07 11:44:36 -06:00
}