简体   繁体   English

使用 exec('command') 方法从 java 执行 linux 命令

[英]Executing linux command from java using exec('command') method

I am trying to execute a Linux command from my java class using the method exec() from the Runtime class in this way:我正在尝试从我的 java class 使用方法 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;        
}

The Linux command I want to use is file -bi fileName and it runs well except in the case the fileName has blanks inside, and that is the point.我要使用的 Linux 命令是file -bi fileName ,它运行良好,除非 fileName 里面有空格,这就是重点。

I've already tried to use double quotes and backslash ( \ ) because this method runs in the Linux bash console, but it doesn't run if I pass it as an argument of exec method.我已经尝试使用双引号和反斜杠( \ ),因为此方法在 Linux bash 控制台中运行,但如果我将其作为 exec 方法的参数传递,它不会运行。

Could anyone help me to resolve this issue?谁能帮我解决这个问题?

Maybe you can use ProcessBuilder class.也许您可以使用 ProcessBuilder class。

Perhaps, you should pass an array of Strings to the exec() method at line 9 of your code:也许,您应该在代码的第 9 行将一个字符串数组传递给 exec() 方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM