使用exec('command')方法从Java执行Linux命令

时间:2019-10-18 14:47:19

标签: java linux filenames

我试图以这种方式使用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,它运行得很好,除非fileName里面有空格,这就是重点。

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

有人可以帮助我解决此问题吗?

2 个答案:

答案 0 :(得分:0)

也许您可以使用ProcessBuilder类。

答案 1 :(得分:0)

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

class MyTest : public ::testing::Test {
protected:
    static MyClassToBeTested my_class;
    static void SetUpTestSuite() {
        //doing some stuff here
    }
};
TEST_F(MyTest, first_test) {
    ASSERT_EQ(my_class.foo(), 5);
}