List of usage examples for java.nio.file PathMatcher matches
boolean matches(Path path);
From source file:Main.java
public static void main(String[] args) { String globPattern = "glob:**txt"; PathMatcher matcher = FileSystems.getDefault().getPathMatcher(globPattern); Path path = Paths.get("C:\\Java_Dev\\test1.txt"); boolean matched = matcher.matches(path); System.out.format("%s matches %s: %b%n", globPattern, path, matched); }
From source file:Test.java
public static void main(String[] args) { Path directory = Paths.get("C:/Program Files/Java/jdk1.7.0/bin"); PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:java?.exe"); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory, "java*.exe")) { for (Path file : directoryStream) { if (pathMatcher.matches(file.getFileName())) { System.out.println(file.getFileName()); }/* ww w .j a v a 2s . co m*/ } } catch (IOException | DirectoryIteratorException ex) { ex.printStackTrace(); } }
From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java
/** * @param args//from www. ja v a 2 s.com */ public static void main(String[] args) { // process command-line options Options options = new Options(); options.addOption("n", "noaddr", false, "do not do any address matching (for testing)"); options.addOption("i", "info", false, "create and populate address information table"); options.addOption("h", "help", false, "this message"); // database connection options.addOption("s", "server", true, "database server to connect to"); options.addOption("d", "database", true, "OSM database name"); options.addOption("u", "user", true, "OSM database user name"); options.addOption("p", "pass", true, "OSM database password"); // logging options options.addOption("l", "logdir", true, "log file directory (default './logs')"); options.addOption("e", "loglevel", true, "log level (default 'FINEST')"); // automatically generate the help statement HelpFormatter help_formatter = new HelpFormatter(); // database URI for connection String dburi = null; // Information message for help screen String info_msg = "IzbirkomExtractor [options] <html_directory>"; try { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h') || cmd.getArgs().length != 1) { help_formatter.printHelp(info_msg, options); System.exit(1); } /* prohibit n and i together */ if (cmd.hasOption('n') && cmd.hasOption('i')) { System.err.println("Options 'n' and 'i' cannot be used together."); System.exit(1); } /* require database arguments without -n */ if (cmd.hasOption('n') && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) { System.err.println("Options 'n' and does not need any databse parameters."); System.exit(1); } /* require all 4 database options to be used together */ if (!cmd.hasOption('n') && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) { System.err.println( "For database access all of the following arguments have to be specified: server, database, user, pass"); System.exit(1); } /* useful variables */ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm"); String dateString = formatter.format(new Date()); /* setup logging */ File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs"); FileUtils.forceMkdir(logdir); File log_file_name = new File( logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log"); FileHandler log_file = new FileHandler(log_file_name.getPath()); /* create "latest" link to currently created log file */ Path latest_log_link = Paths.get(logdir + "/latest"); Files.deleteIfExists(latest_log_link); Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName())); log_file.setFormatter(new SimpleFormatter()); LogManager.getLogManager().reset(); // prevents logging to console logger.addHandler(log_file); logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST); // open directory with HTML files and create file list File dir = new File(cmd.getArgs()[0]); if (!dir.isDirectory()) { System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting"); System.exit(1); } PathMatcher pmatcher = FileSystems.getDefault() .getPathMatcher("glob:? * ?*.html"); ArrayList<File> html_files = new ArrayList<>(); for (Path file : Files.newDirectoryStream(dir.toPath())) if (pmatcher.matches(file.getFileName())) html_files.add(file.toFile()); if (html_files.size() == 0) { System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting"); System.exit(1); } // create csvResultSink FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv"); OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8"); ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#')); // Connect to DB and osmAddressMatcher AddressMatcher osmAddressMatcher; DBSink dbSink = null; DBInfoSink dbInfoSink = null; if (cmd.hasOption('n')) { osmAddressMatcher = new DummyAddressMatcher(); } else { dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d'); Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'), cmd.getOptionValue('p')); osmAddressMatcher = new OsmAddressMatcher(con); dbSink = new DBSink(con); if (cmd.hasOption('i')) dbInfoSink = new DBInfoSink(con); } /* create resultsinks */ SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor(); sm.addResultSink(csvResultSink); if (dbSink != null) { sm.addResultSink(dbSink); if (dbInfoSink != null) sm.addResultSink(dbInfoSink); } // create tableExtractor TableExtractor te = new TableExtractor(osmAddressMatcher, sm); // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters // iterate through files logger.info("Start processing " + html_files.size() + " files in " + dir); for (int i = 0; i < html_files.size(); i++) { System.err.println("Parsing #" + i + ": " + html_files.get(i)); te.processHTMLfile(html_files.get(i)); } System.err.println("Processed " + html_files.size() + " HTML files"); logger.info("Finished processing " + html_files.size() + " files in " + dir); } catch (ParseException e1) { System.err.println("Failed to parse CLI: " + e1.getMessage()); help_formatter.printHelp(info_msg, options); System.exit(1); } catch (IOException e) { System.err.println("I/O Exception: " + e.getMessage()); e.printStackTrace(); System.exit(1); } catch (SQLException e) { System.err.println("Database '" + dburi + "': " + e.getMessage()); System.exit(1); } catch (ResultSinkException e) { System.err.println("Failed to initialize ResultSink: " + e.getMessage()); System.exit(1); } catch (TableExtractorException e) { System.err.println("Failed to initialize Table Extractor: " + e.getMessage()); System.exit(1); } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) { System.err.println("Something really odd happened: " + e.getMessage()); e.printStackTrace(); System.exit(1); } }
From source file:edu.wpi.checksims.submission.Submission.java
/** * Identify all files matching in a single directory. * * @param directory Directory to find files within * @param glob Match pattern used to identify files to include * @return Array of files which match in this single directory *///from ww w .j av a 2 s . c o m static File[] getMatchingFilesFromDir(File directory, String glob) throws NoSuchFileException, NotDirectoryException { checkNotNull(directory); checkNotNull(glob); checkArgument(!glob.isEmpty(), "Glob pattern cannot be empty"); PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob); if (!directory.exists()) { throw new NoSuchFileException("Does not exist: " + directory.getAbsolutePath()); } else if (!directory.isDirectory()) { throw new NotDirectoryException("Not a directory: " + directory.getAbsolutePath()); } return directory.listFiles((f) -> matcher.matches(Paths.get(f.getAbsolutePath()).getFileName())); }
From source file:net.lldp.checksims.submission.Submission.java
/** * Recursively find all files matching in a directory. * * @param directory Directory to search in * @param glob Match pattern used to identify files to include * @return List of all matching files in this directory and subdirectories *//*from w w w.j ava2 s . c om*/ static Set<File> getAllMatchingFiles(File directory, String glob, boolean recursive) throws NoSuchFileException, NotDirectoryException { checkNotNull(directory); checkNotNull(glob); checkArgument(!glob.isEmpty(), "Glob pattern cannot be empty"); if (!directory.exists()) { throw new NoSuchFileException("Does not exist: " + directory.getAbsolutePath()); } else if (!directory.isDirectory()) { throw new NotDirectoryException("Not a directory: " + directory.getAbsolutePath()); } PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob); Set<File> allFiles = new HashSet<>(); Logger logs = LoggerFactory.getLogger(Submission.class); if (recursive) { logs.trace("Recursively traversing directory " + directory.getName()); } // Get files in this directory File[] contents = directory .listFiles((f) -> matcher.matches(Paths.get(f.getAbsolutePath()).getFileName()) && f.isFile()); // TODO consider mapping to absolute paths? // Add this directory Collections.addAll(allFiles, contents); // Get subdirectories File[] subdirs = directory.listFiles(File::isDirectory); // Recursively call on all subdirectories if specified if (recursive) { for (File subdir : subdirs) { allFiles.addAll(getAllMatchingFiles(subdir, glob, true)); } } return allFiles; }
From source file:de.ingrid.interfaces.csw.tools.FileUtils.java
/** * Delete a file or directory specified by a {@link Path}. This method uses * the new {@link Files} API and allows to specify a regular expression to * remove only files that match that expression. * /* ww w . j a va2 s . c o m*/ * @param path * @param pattern * @throws IOException */ public static void deleteRecursive(Path path, final String pattern) throws IOException { final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:" + pattern); if (!Files.exists(path)) return; Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (pattern != null && matcher.matches(file.getFileName())) { Files.delete(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { // try to delete the file anyway, even if its attributes // could not be read, since delete-only access is // theoretically possible if (pattern != null && matcher.matches(file.getFileName())) { Files.delete(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { if (matcher.matches(dir.getFileName())) { if (dir.toFile().list().length > 0) { // remove even if not empty FileUtils.deleteRecursive(dir); } else { Files.delete(dir); } } return FileVisitResult.CONTINUE; } else { // directory iteration failed; propagate exception throw exc; } } }); }
From source file:com.expedia.tesla.compiler.Util.java
/** * Expand glob file patterns to path strings. Any path element that is not a glob pattern will be keep as it is. * /*from w w w.j av a 2 s . c o m*/ * @param pathOrPatterns * glob patterns. * * @return * The expanded paths. * * @throws IOException * On IO errors. */ public static Collection<String> expandWildcard(Collection<String> pathOrPatterns) throws IOException { final List<String> files = new ArrayList<String>(); final List<PathMatcher> matchers = new ArrayList<PathMatcher>(); for (String pattern : pathOrPatterns) { if (pattern.contains("*") || pattern.contains("?")) { PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); matchers.add(matcher); } else { files.add(pattern); } } if (!matchers.isEmpty()) { Files.walkFileTree(new File(System.getProperty("user.dir")).toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attr) { for (PathMatcher matcher : matchers) { if (matcher.matches(file)) { files.add(file.toString()); } } return FileVisitResult.CONTINUE; } }); } return files; }
From source file:gedi.util.FileUtils.java
public static String[] find(String path, String glob, boolean stripPath) throws IOException { if (!path.endsWith("/")) path = path + "/"; String cpath = path;//w ww .ja va 2s . c om ArrayList<String> re = new ArrayList<String>(); PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + path + glob); Files.find(Paths.get(path), 9999, (p, per) -> { return matcher.matches(p); }, FileVisitOption.FOLLOW_LINKS).forEach(f -> { String file = f.toString(); if (stripPath && file.startsWith(cpath)) file = file.substring(cpath.length()); re.add(file); }); return re.toArray(new String[0]); }
From source file:com.esri.geoportal.harvester.unc.UncFolder.java
/** * Matches file//w ww.j a va 2s . c o m * @param file file * @param pattern match patter (glob) * @return <code>true</code> if URL matches the pattern */ private boolean matchFileName(File file, String pattern) { Path path = file.toPath(); PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:" + pattern); return pathMatcher.matches(path); }
From source file:com.esri.geoportal.harvester.waf.WafFolder.java
/** * Matches URL/*from w w w . ja va2 s . c om*/ * @param u url * @param pattern match patter (glob) * @return <code>true</code> if URL matches the pattern */ private boolean matchUrl(URL u, String pattern) { String[] split = u.getPath().split("(/|\\\\)+"); List<String> items = Arrays.asList(split).stream().filter(s -> s != null && !s.isEmpty()) .collect(Collectors.toList()); if (!items.isEmpty()) { String first = items.get(0); List<String> subList = items.subList(1, items.size()); Path path = fileSystem.getPath(first, subList.toArray(new String[] {})); PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:" + pattern); return pathMatcher.matches(path); } else { return false; } }