X-Git-Url: http://source.jalview.org/gitweb/?a=blobdiff_plain;f=src%2Fjalview%2Futil%2FFileUtils.java;h=3652448d24952cc30dc37ea7c1afae24a07a6cff;hb=f79386294ab0078db7bd88d294d646c990dcfbcf;hp=1684763e6822be31ef41d25ac39e266277a496d0;hpb=f37c3fd4fe12799de498de5f397252e9f457fee9;p=jalview.git diff --git a/src/jalview/util/FileUtils.java b/src/jalview/util/FileUtils.java index 1684763..3652448 100644 --- a/src/jalview/util/FileUtils.java +++ b/src/jalview/util/FileUtils.java @@ -2,6 +2,12 @@ package jalview.util; import java.io.File; import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.PathMatcher; +import java.util.ArrayList; +import java.util.List; /** * Miscellaneous file-related functions @@ -75,4 +81,42 @@ public final class FileUtils return f; } + /** + * Answers a (possibly empty) list of file paths found by searching below + * from that match the supplied regular expression + * pattern. Results may include from itself if it + * matches. If an exception occurs it is written to syserr and any results up + * to that point are returned. Note that the regular expression match applies + * to the whole path of any matched file. + *

+ * Because the whole directory tree below from is searched, this + * method may be slow if used for a high level directory. + * + *

+   * Example: 
+   *   findMatchingPaths(".*/chimera.exe$", Paths.get("C:/Program Files"))
+   * 
+ * + * @param pattern + * @param from + * @return + * @see https://stackoverflow.com/questions/794381/how-to-find-files-that-match-a-wildcard-string-in-java/31685610#comment62441832_31685610 + */ + public static List findMatchingPaths(String pattern, Path from) + { + List matches = new ArrayList<>(); + PathMatcher pathMatcher = FileSystems.getDefault() + .getPathMatcher("regex:" + pattern); + try + { + Files.walk(from).filter(pathMatcher::matches) + .forEach(m -> matches.add(m.toString())); + } catch (IOException e) + { + System.err.println( + "Error searching for " + pattern + " : " + e.toString()); + } + + return matches; + } }