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 */ public final class FileUtils { /** * Answers the executable file for the given command, or null if not found or * not executable. The path to the executable is the command name prefixed by * the given folder path, optionally with .exe appended. * * @param cmd * command short name, for example hmmbuild * @param binaryPath * parent folder for the executable * @return */ public static File getExecutable(String cmd, String binaryPath) { File file = new File(binaryPath, cmd); if (!file.canExecute()) { file = new File(binaryPath, cmd + ".exe"); { if (!file.canExecute()) { file = null; } } } return file; } /** * Answers the path to the folder containing the given executable file, by * searching the PATH environment variable. Answers null if no such executable * can be found. * * @param cmd * @return */ public static String getPathTo(String cmd) { String paths = System.getenv("PATH"); // backslash is to escape regular expression argument for (String path : paths.split("\\" + File.pathSeparator)) { if (getExecutable(cmd, path) != null) { return path; } } return null; } /** * A convenience method to create a temporary file that is deleted on exit of * the JVM * * @param prefix * @param suffix * @return * @throws IOException */ public static File createTempFile(String prefix, String suffix) throws IOException { File f = File.createTempFile(prefix, suffix); f.deleteOnExit(); 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; } }