1684763e6822be31ef41d25ac39e266277a496d0
[jalview.git] / src / jalview / util / FileUtils.java
1 package jalview.util;
2
3 import java.io.File;
4 import java.io.IOException;
5
6 /**
7  * Miscellaneous file-related functions
8  */
9 public final class FileUtils
10 {
11
12   /**
13    * Answers the executable file for the given command, or null if not found or
14    * not executable. The path to the executable is the command name prefixed by
15    * the given folder path, optionally with .exe appended.
16    * 
17    * @param cmd
18    *          command short name, for example hmmbuild
19    * @param binaryPath
20    *          parent folder for the executable
21    * @return
22    */
23   public static File getExecutable(String cmd, String binaryPath)
24   {
25     File file = new File(binaryPath, cmd);
26     if (!file.canExecute())
27     {
28       file = new File(binaryPath, cmd + ".exe");
29       {
30         if (!file.canExecute())
31         {
32           file = null;
33         }
34       }
35     }
36     return file;
37   }
38
39   /**
40    * Answers the path to the folder containing the given executable file, by
41    * searching the PATH environment variable. Answers null if no such executable
42    * can be found.
43    * 
44    * @param cmd
45    * @return
46    */
47   public static String getPathTo(String cmd)
48   {
49     String paths = System.getenv("PATH");
50     // backslash is to escape regular expression argument
51     for (String path : paths.split("\\" + File.pathSeparator))
52     {
53       if (getExecutable(cmd, path) != null)
54       {
55         return path;
56       }
57     }
58     return null;
59   }
60
61   /**
62    * A convenience method to create a temporary file that is deleted on exit of
63    * the JVM
64    * 
65    * @param prefix
66    * @param suffix
67    * @return
68    * @throws IOException
69    */
70   public static File createTempFile(String prefix, String suffix)
71           throws IOException
72   {
73     File f = File.createTempFile(prefix, suffix);
74     f.deleteOnExit();
75     return f;
76   }
77
78 }