本文整理汇总了Java中java.nio.file.PathMatcher类的典型用法代码示例。如果您正苦于以下问题:Java PathMatcher类的具体用法?Java PathMatcher怎么用?Java PathMatcher使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
PathMatcher类属于java.nio.file包,在下文中一共展示了PathMatcher类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getConfig
import java.nio.file.PathMatcher; //导入依赖的package包/类
@Override
public Config getConfig() throws IOException {
PathMatcher pathMatcher;
try {
pathMatcher = FileSystems.getDefault().getPathMatcher(inputFilePattern);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
"Invalid input file pattern: " + inputFilePattern);
}
try (Stream<Path> pathStream = Files.walk(baseDirectory)) {
return pathStream
.filter(p -> Files.isRegularFile(p) && pathMatcher.matches(p))
.map(p -> ConfigFactory.parseFile(p.toFile()))
.reduce(ConfigFactory.empty(), Config::withFallback)
.resolve(
ConfigResolveOptions.defaults()
.setAllowUnresolved(true)
.setUseSystemEnvironment(false)
);
}
}
示例2: loadDatabaseReaders
import java.nio.file.PathMatcher; //导入依赖的package包/类
static Map<String, DatabaseReaderLazyLoader> loadDatabaseReaders(Path geoIpConfigDirectory, NodeCache cache) throws IOException {
if (Files.exists(geoIpConfigDirectory) == false && Files.isDirectory(geoIpConfigDirectory)) {
throw new IllegalStateException("the geoip directory [" + geoIpConfigDirectory + "] containing databases doesn't exist");
}
Map<String, DatabaseReaderLazyLoader> databaseReaders = new HashMap<>();
try (Stream<Path> databaseFiles = Files.list(geoIpConfigDirectory)) {
PathMatcher pathMatcher = geoIpConfigDirectory.getFileSystem().getPathMatcher("glob:**.mmdb.gz");
// Use iterator instead of forEach otherwise IOException needs to be caught twice...
Iterator<Path> iterator = databaseFiles.iterator();
while (iterator.hasNext()) {
Path databasePath = iterator.next();
if (Files.isRegularFile(databasePath) && pathMatcher.matches(databasePath)) {
String databaseFileName = databasePath.getFileName().toString();
DatabaseReaderLazyLoader holder = new DatabaseReaderLazyLoader(databaseFileName, () -> {
try (InputStream inputStream = new GZIPInputStream(Files.newInputStream(databasePath, StandardOpenOption.READ))) {
return new DatabaseReader.Builder(inputStream).withCache(cache).build();
}
});
databaseReaders.put(databaseFileName, holder);
}
}
}
return Collections.unmodifiableMap(databaseReaders);
}
示例3: testGlobPath
import java.nio.file.PathMatcher; //导入依赖的package包/类
@Test
public void testGlobPath() {
PathMatcher matcher = MetricTree.createPathMatcher("asdf[");
assertNull(matcher);
Multimap<String, String> pattern2Candidates = generate();
for (Map.Entry<String, Collection<String>> pattern2CandidatesMap : pattern2Candidates.asMap().entrySet()) {
String glob = pattern2CandidatesMap.getKey();
matcher = MetricTree.createPathMatcher(glob);
if (matcher == null) {
System.out.println("Wrong pattern " + glob);
continue;
}
for (String node : pattern2CandidatesMap.getValue()) {
System.out.println(String.format("%40s\t%40s\t%s", glob, node, MetricTree.matches(matcher, node)));
}
}
}
示例4: read
import java.nio.file.PathMatcher; //导入依赖的package包/类
/**
* Reads in the given JSON file and parses the content.
* Creates and returns a new settings object with it.
*
* @param path path to JSON file
* @return settings object or null if impossible to read
* @throws IllegalArgumentException if the given path is null
* @throws FileNotFoundException if the given path can not be found
*/
public static Settings read(Path path) throws IllegalArgumentException, FileNotFoundException {
if (path == null) {
throw new IllegalArgumentException("The given file path is not initialized.");
}
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.json");
if (!matcher.matches(path)) {
throw new IllegalArgumentException("The file ending does not match .json.");
}
Settings settings = null;
// parse JSON document to a java object
JSONSettings json = new Gson().fromJson(new FileReader(path.toFile()), JSONSettings.class);
if (json != null) {
// create the actual settings object with the information of the read in objects
settings = new Settings(json);
}
return settings;
}
示例5: TaildirMatcher
import java.nio.file.PathMatcher; //导入依赖的package包/类
/**
* Package accessible constructor. From configuration context it represents a single
* <code>filegroup</code> and encapsulates the corresponding <code>filePattern</code>.
* <code>filePattern</code> consists of two parts: first part has to be a valid path to an
* existing parent directory, second part has to be a valid regex
* {@link java.util.regex.Pattern} that match any non-hidden file names within parent directory
* . A valid example for filePattern is <code>/dir0/dir1/.*</code> given
* <code>/dir0/dir1</code> is an existing directory structure readable by the running user.
* <p></p>
* An instance of this class is created for each fileGroup
*
* @param fileGroup arbitrary name of the group given by the config
* @param filePattern parent directory plus regex pattern. No wildcards are allowed in directory
* name
* @param cachePatternMatching default true, recommended in every setup especially with huge
* parent directories. Don't set when local system clock is not used
* for stamping mtime (eg: remote filesystems)
* @see TaildirSourceConfigurationConstants
*/
TaildirMatcher(String fileGroup, String filePattern, boolean cachePatternMatching) {
// store whatever came from configuration
this.fileGroup = fileGroup;
this.filePattern = filePattern;
this.cachePatternMatching = cachePatternMatching;
// calculate final members
File f = new File(filePattern);
this.parentDir = f.getParentFile();
String regex = f.getName();
final PathMatcher matcher = FS.getPathMatcher("regex:" + regex);
this.fileFilter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return matcher.matches(entry.getFileName()) && !Files.isDirectory(entry);
}
};
// sanity check
Preconditions.checkState(parentDir.exists(),
"Directory does not exist: " + parentDir.getAbsolutePath());
}
示例6: listClassNamesInPackage
import java.nio.file.PathMatcher; //导入依赖的package包/类
static List<String> listClassNamesInPackage(String packageName) throws Exception {
List<String> classes = new ArrayList<>();
Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packageName.replace('.', File.separatorChar));
if (!resources.hasMoreElements()) {
throw new IllegalStateException("No package found: " + packageName);
}
PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:*.class");
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
Files.walkFileTree(Paths.get(resource.toURI()), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (pathMatcher.matches(path.getFileName())) {
try {
String className = Paths.get(resource.toURI()).relativize(path).toString().replace(File.separatorChar, '.');
classes.add(packageName + '.' + className.substring(0, className.length() - 6));
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
return FileVisitResult.CONTINUE;
}
});
}
return classes;
}
示例7: readFileWithPattern
import java.nio.file.PathMatcher; //导入依赖的package包/类
public static List<String> readFileWithPattern(File path) {
PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + path.getAbsolutePath());
List<String> result = new ArrayList<String>();
String p = path.getAbsolutePath();
int index = p.lastIndexOf(File.separator);
if(index == -1) {
throw new IllegalArgumentException("Cannot parse path:" + p + ", please use like this : /f/example/*.bgz ");
}
File dir = new File(p.substring(0, index));
File[] files = dir.listFiles();
for (File file : files) {
if(pathMatcher.matches(file.toPath())) {
result.add(file.getAbsolutePath());
}
}
// if(result.size() > MAX_FILE) {
// throw new IllegalArgumentException("Cannot handle files more than " + MAX_FILE + " at one time, please merge file first." );
// }
return result;
}
示例8: getPathMatcher
import java.nio.file.PathMatcher; //导入依赖的package包/类
@Override
public PathMatcher getPathMatcher(String syntaxAndInput) {
int pos = syntaxAndInput.indexOf(':');
if (pos <= 0 || pos == syntaxAndInput.length()) {
throw new IllegalArgumentException("pos is " + pos);
}
String syntax = syntaxAndInput.substring(0, pos);
String input = syntaxAndInput.substring(pos + 1);
String expr;
if (syntax.equalsIgnoreCase("glob")) {
expr = JrtUtils.toRegexPattern(input);
} else if (syntax.equalsIgnoreCase("regex")) {
expr = input;
} else {
throw new UnsupportedOperationException("Syntax '" + syntax
+ "' not recognized");
}
// return matcher
final Pattern pattern = Pattern.compile(expr);
return (Path path) -> pattern.matcher(path.toString()).matches();
}
示例9: getPathMatcher
import java.nio.file.PathMatcher; //导入依赖的package包/类
@Override
public PathMatcher getPathMatcher(String syntaxAndInput) {
int pos = syntaxAndInput.indexOf(':');
if (pos <= 0 || pos == syntaxAndInput.length()) {
throw new IllegalArgumentException();
}
String syntax = syntaxAndInput.substring(0, pos);
String input = syntaxAndInput.substring(pos + 1);
String expr;
if (syntax.equalsIgnoreCase("glob")) {
expr = JrtUtils.toRegexPattern(input);
} else if (syntax.equalsIgnoreCase("regex")) {
expr = input;
} else {
throw new UnsupportedOperationException("Syntax '" + syntax
+ "' not recognized");
}
// return matcher
final Pattern pattern = Pattern.compile(expr);
return (Path path) -> pattern.matcher(path.toString()).matches();
}
示例10: newDirectoryStream
import java.nio.file.PathMatcher; //导入依赖的package包/类
/**
* Opens a directory stream on provided 'dir' folder, filtering file names according
* to the provided glob syntax.
* <p>
* See http://blog.eyallupu.com/2011/11/java-7-working-with-directories.html
*
* @param dir the directory to read from
* @param glob the glob matching
* @return the opened DirectoryStream (remaining to be closed)
* @throws IOException
*/
public static DirectoryStream newDirectoryStream (Path dir,
String glob)
throws IOException
{
// create a matcher and return a filter that uses it.
final FileSystem fs = dir.getFileSystem();
final PathMatcher matcher = fs.getPathMatcher("glob:" + glob);
final DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>()
{
@Override
public boolean accept (Path entry)
{
return matcher.matches(entry.getFileName());
}
};
return fs.provider().newDirectoryStream(dir, filter);
}
示例11: getPathMatcher
import java.nio.file.PathMatcher; //导入依赖的package包/类
@Override
public PathMatcher getPathMatcher( String syntaxAndInput )
{
int pos = syntaxAndInput.indexOf( ':' );
if( pos <= 0 || pos == syntaxAndInput.length() ) {
throw new IllegalArgumentException();
}
String syntax = syntaxAndInput.substring( 0, pos );
String input = syntaxAndInput.substring( pos + 1 );
String expr;
if( syntax.equals( REGEX_SYNTAX ) ) {
expr = input;
}
else {
throw new UnsupportedOperationException( "Syntax '" + syntax + "' not recognized" );
}
// return matcher
final Pattern pattern = Pattern.compile( expr );
return path -> pattern.matcher( path.toString() ).matches();
}
示例12: getPathMatcher
import java.nio.file.PathMatcher; //导入依赖的package包/类
@Override
public PathMatcher getPathMatcher(final String syntaxAndPattern) {
final int pos = syntaxAndPattern.indexOf(':');
if (pos <= 0 || pos == syntaxAndPattern.length()) {
throw new IllegalArgumentException();
}
final String syntax = syntaxAndPattern.substring(0, pos);
final String pattern = syntaxAndPattern.substring(pos + 1);
switch (syntax) {
case "glob":
return new MCRGlobPathMatcher(pattern);
case "regex":
return new MCRPathMatcher(pattern);
default:
throw new UnsupportedOperationException("If the pattern syntax '" + syntax + "' is not known.");
}
}
示例13: get
import java.nio.file.PathMatcher; //导入依赖的package包/类
public static ESLintIgnore get(FileObject fileObject) {
if (fileObject.isFolder() && fileObject.getFileObject(".eslintignore") != null) {
try {
FileObject ignore = fileObject.getFileObject(".eslintignore");
List<PathMatcher> pathMatchers = new ArrayList<>();
final List<String> lines = ignore.asLines();
for (String glob : lines) {
glob = glob.endsWith("/") ? glob + "**/*" : glob;
pathMatchers.add(FileSystems.getDefault().getPathMatcher("glob:" + glob));
}
return new ESLintIgnore(fileObject, pathMatchers);
} catch (IOException iOException) {
Logger.getLogger(ESLintIgnore.class.getName()).log(Level.WARNING, "Failed to read ignore file");
return new ESLintIgnore(fileObject, Collections.EMPTY_LIST);
}
} else if (fileObject.isFolder()) {
return new ESLintIgnore(fileObject, Collections.EMPTY_LIST);
} else {
throw new IllegalArgumentException("Not a folder " + fileObject);
}
}
示例14: FileVisitor
import java.nio.file.PathMatcher; //导入依赖的package包/类
public FileVisitor(PathMatcher pathMatcher, List<File> paths, File startDir, Operation operation) {
mStartDir = startDir;
mOperation = operation;
mOperationListener = operation.getListener();
mFiles = paths;
mPathMatcher = pathMatcher;
mExcludePatterns = StringUtils.split(operation.getExcludePattern(), "::");
mDirToDesc = operation.getDirToDesc();
final DescriptionMode mode = operation.getProfileDescription().getMode();
mUseExternalDescription = mode == DescriptionMode.EXTERNAL;
mExternalFileValue = operation.getProfileDescription().getExternalFileValue();
if (mode == DescriptionMode.EXTERNAL) {
try {
File file = new File(startDir, mExternalFileValue);
if (file.isFile()) {
mDefaultDescProperties.load(new InputStreamReader(new FileInputStream(file), Charset.defaultCharset()));
}
} catch (IOException ex) {
// nvm
}
}
}
示例15: match
import java.nio.file.PathMatcher; //导入依赖的package包/类
/** Search for a glob pattern in a given directory and its sub directories
* See http://javapapers.com/java/glob-with-java-nio/
* */
private static List<Path> match(String glob, String location) throws IOException {
final List<Path> globbed= new ArrayList<Path>();
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);
Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (pathMatcher.matches(path)) {
globbed.add(path);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
return FileVisitResult.CONTINUE;
}
});
return globbed;
}