【问题标题】:Executing linux command from java using exec('command') method使用 exec('command') 方法从 java 执行 linux 命令
【发布时间】:2019-10-18 14:47:19
【问题描述】:

我正在尝试以这种方式使用 Runtime 类中的方法 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,它运行良好,除非文件名里面有空格,这就是重点。

我已经尝试使用双引号和反斜杠 (\),因为此方法在 Linux bash 控制台中运行,但如果我将其作为 exec 方法的参数传递,它不会运行。

谁能帮我解决这个问题?

【问题讨论】:

    标签: java linux filenames


    【解决方案1】:

    也许,您应该在代码的第 9 行将一个字符串数组传递给 exec() 方法:

    p = r.exec(new String[]{ "file", "-bi", sPath, sFileName});
    

    【讨论】:

    • 谢谢。它运行,但有一点变化。
    • 解决方法是:'p = r.exec(new String[]{ "file", "-bi", sPath + sFileName});'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多