簡體   English   中英

使用 exec('command') 方法從 java 執行 linux 命令

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

我正在嘗試從我的 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;        
}

我要使用的 Linux 命令是file -bi fileName ,它運行良好,除非 fileName 里面有空格,這就是重點。

我已經嘗試使用雙引號和反斜杠( \ ),因為此方法在 Linux bash 控制台中運行,但如果我將其作為 exec 方法的參數傳遞,它不會運行。

誰能幫我解決這個問題?

也許您可以使用 ProcessBuilder class。

也許,您應該在代碼的第 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