Created
May 15, 2016 14:36
-
-
Save tiqwab/19f983be91bf4c4038ff551b751580f1 to your computer and use it in GitHub Desktop.
List files with antInclude
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Depends on commons-io