我正在尝试以这种方式使用运行时类中的方法 exec() 从我的 java 类中执行 Linux 命令:
public static String xxUtilInfoFile (String sPath , String sFileName) throws Exception
{
Runtime r = null;
Process p = null;
String line_value="";
String output_data="";
/*execute the process*/
r = Runtime.getRuntime();
p = r.exec("file -bi " + sPath + sFileName);
p.waitFor();
/*Return the standard error output*/
BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
output_data = in.readLine();
return output_data;
}
我想使用的 Linux 命令是 file -bi fileName
,它运行良好,除非 fileName 内部有空格,这就是重点。
我已经尝试使用双引号和反斜杠 (\
) 因为这个方法在 Linux bash 控制台中运行,但是如果我将它作为 exec 方法的参数传递它就不会运行.
谁能帮我解决这个问题?
最佳答案
或许,您应该在代码的第 9 行将一个字符串数组传递给 exec() 方法:
p = r.exec(new String[]{ "file", "-bi", sPath, sFileName});
关于java - 使用 exec ('command' ) 方法从 java 执行 linux 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58453211/