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

问题描述 投票:0回答:1

我正在尝试以这种方式使用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方法的参数传递,它将无法运行。

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

提前感谢。

java linux filenames
1个回答
0
投票

也许您可以使用ProcessBuilder类。https://www.mkyong.com/java/java-processbuilder-examples/

© www.soinside.com 2019 - 2024. All rights reserved.