是否可以在Java中获取shell命令引用的文件路径?
例如,当我在Windows命令提示符下键入php -v
时,它会知道我指的是C:\php\php.exe
(对于我自己的计算机),因为我将其添加到系统Path变量中。是否有可能在Java中做同样的事情?
我知道您可以从Java获取Path环境变量并使用String.split(";")
解析它,但我想知道是否有更直接的方法?
答案 0 :(得分:2)
查看JGit lib中的以下代码 http://download.eclipse.org/jgit/site/3.7.1.201504261725-r/apidocs/org/eclipse/jgit/util/FS.html#searchPath(java.lang.String,%20java.lang.String...)
你可以实现类似的东西
/**
* Searches the given path to see if it contains one of the given files.
* Returns the first it finds. Returns null if not found or if path is null.
*
* @param path
* List of paths to search separated by File.pathSeparator
* @param lookFor
* Files to search for in the given path
* @return the first match found, or null
* @since 3.0
**/
protected static File searchPath(final String path, final String... lookFor) {
if (path == null)
return null;
for (final String p : path.split(File.pathSeparator)) {
for (String command : lookFor) {
final File e = new File(p, command);
if (e.isFile())
return e.getAbsoluteFile();
}
}
return null;
}
答案 1 :(得分:1)
您可以使用my Java Command Prompt中的此摘录执行某些操作。
String cmd = "which "+<insert executable to find>; // linux
String cmd = "where "+<insert executable to find>; // windows
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
while ((s = stdInput.readLine()) != null) {
ref.log.setText(ref.log.getText()+s+"\n");
ref.updateDisplay();
}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
ref.log.setText(ref.log.getText()+s+"\n");
ref.updateDisplay();
}
输出应包含文件的路径。