Skip to content

Instantly share code, notes, and snippets.

@tiqwab
Created May 15, 2016 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiqwab/19f983be91bf4c4038ff551b751580f1 to your computer and use it in GitHub Desktop.
Save tiqwab/19f983be91bf4c4038ff551b751580f1 to your computer and use it in GitHub Desktop.
List files with antInclude
package org.tiqwab.util;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.io.FilenameUtils;
public class FileUtils {
private static final String PATH_SEPARATOR = "/";
/**
* List files from path containing wild card such as '*' and '?' <br>
* For example, if there are three files, 'a/b/c/d.txt', 'a/b/d.txt', and 'a/b/c/d.bmp': <br>
* antInclude: 'a/b/c/*.txt' -> 'a/b/c/d.txt' <br>
* antInclude: 'a/b/c/?.*' -> 'a/b/c/d.txt', 'a/b/c/d.bmp' <br>
* @param antInclude
* @return files matching the specified pattern
*/
public static File[] listFiles(String antInclude) {
Objects.requireNonNull(antInclude, "antInclude must not be null");
String includeNormalized = FilenameUtils.separatorsToUnix(antInclude);
PathInfo pathInfo = separatePath(includeNormalized);
return listFiles(new File(pathInfo.getPathToBaseDir()), pathInfo.getPattern());
}
private static File[] listFiles(File baseDir, String pattern) {
List<File> fileList = new ArrayList<>();
for (File file : baseDir.listFiles()) {
if (file.isFile()) {
if (FilenameUtils.wildcardMatchOnSystem(file.getName(), pattern)) {
fileList.add(file);
}
}
}
return fileList.toArray(new File[0]);
}
private static PathInfo separatePath(String pattern) {
int indexSep = pattern.lastIndexOf(PATH_SEPARATOR);
return (indexSep < 0)
? new PathInfo(".", pattern)
: new PathInfo(pattern.substring(0, indexSep), pattern.substring(indexSep+1));
}
private static class PathInfo {
private String pathToBaseDir;
private String pattern;
PathInfo(String pathToBaseDir, String pattern) {
this.pathToBaseDir = pathToBaseDir;
this.pattern = pattern;
}
public String getPathToBaseDir() {
return this.pathToBaseDir;
}
public String getPattern() {
return this.pattern;
}
}
}
@tiqwab
Copy link
Author

tiqwab commented May 15, 2016

Depends on commons-io

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment