Skip to content

Instantly share code, notes, and snippets.

@Pozo
Created January 19, 2016 14:03
Show Gist options
  • Save Pozo/b1ab957adb2c54c55e22 to your computer and use it in GitHub Desktop.
Save Pozo/b1ab957adb2c54c55e22 to your computer and use it in GitHub Desktop.
List files in a path which having wildcards with Java1.6
public class App {
private static final String PATTERN = "D:\\maven-repository\\commons-cli\\commons-cli\\1.0\\commons-cli-.*.jar";
public static void main(String[] args) {
List<File> matches = new ArrayList<File>();
String[] pieces = PATTERN.split("\\.\\*");
if(pieces.length >= 2) {
File rootFile = getRootFile(pieces[0]);
String remainingPath = PATTERN.substring(rootFile.getPath().length()+1, PATTERN.length());
String[] remainingPieces = remainingPath.split("\\\\");
LinkedList<String> regexes = new LinkedList<String>();
regexes.addAll(Arrays.asList(remainingPieces));
find(rootFile,0, regexes,matches);
for (File file : matches) {
System.out.println("++" + file);
}
}
}
private static void find(File root, int level , LinkedList<String> regexes, List<File> matches) {
if(root==null) {
return;
}
if(root.isDirectory()) {
String regex = regexes.get(level);
for(File subFolder : root.listFiles()) {
String name = subFolder.getName();
if(name.matches(regex)) {
find(subFolder,level + 1,regexes, matches);
}
}
} else {
matches.add(root);
return;
}
}
private static File getRootFile(String root) {
int lastSlash = root.lastIndexOf("\\");
String rootPath = root.substring(0, lastSlash);
File rootFile = new File(rootPath);
return rootFile;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment