JAL-2994 use pattern matches to search for chimera.exe
[jalview.git] / src / jalview / util / FileUtils.java
index 1684763..3652448 100644 (file)
@@ -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
+   * <code>from</code> that match the supplied regular expression
+   * <code>pattern</code>. Results may include <code>from</code> 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.
+   * <p>
+   * Because the whole directory tree below <code>from</code> is searched, this
+   * method may be slow if used for a high level directory.
+   * 
+   * <pre>
+   * Example: 
+   *   findMatchingPaths(".*&#47chimera.exe$", Paths.get("C:/Program Files"))
+   * </pre>
+   * 
+   * @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<String> findMatchingPaths(String pattern, Path from)
+  {
+    List<String> 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;
+  }
 }