推薦閱讀:
執行函數
Process exec(String command)
在單獨的進程中執行指定的字符串命令
Process exec(String[] cmdarray)
在單獨的進程中執行指定命令和變量
Process exec(String[] cmdarray, String[] envp)
在指定環境的獨立進程中執行指定命令和變量
Process exec(String[] cmdarray, String[] envp, File dir)
在指定環境和工作目錄的獨立進程中執行指定的命令和變量
Process exec(String command, String[] envp)
在指定環境的單獨進程中執行指定的字符串命令
Process exec(String command, String[] envp, File dir)
在有指定環境和工作目錄的獨立進程中執行指定的字符串命令
abstract int waitFor()
導致當前線程等待,如有必要,一直要等到由該 Process 對象表示的進程已經終止
abstract InputStream getInputStream()
獲取子進程的輸入流,最好對輸入流進行緩衝
參數說明:
cmdarray
: 包含所調用命令及其參數的數組。command
: 一條指定的系統命令envp
: 字符串數組,其中每個元素的環境變量的設置格式爲name=value;如果子進程應該繼承當前進程的環境,則該參數爲 nulldir
: 子進程的工作目錄;如果子進程應該繼承當前進程的工作目錄,則該參數爲 null
特別注意
Java 執行 shell 命令的奇怪執行:
步驟:
- 將 shell 命令通過
String[] cmd = {"sh","-c",command}
處理,執行cmd
參數 - 也可以使用 base64 編碼處理特殊字符問題
String command = "xxx"; //shell 命令
String[] cmd = {"sh","-c",cmd}; //很重要
Runtime.getRuntime().exec(cmd); //執行
例子
public class ReadCmdLine {
public static void main(String args[]) {
Process process = null;
List<String> processList = new ArrayList<String>();
try {
String command = "ls -a";
String[] cmd = {"sh","-c",command};
process = Runtime.getRuntime().exec(cmd);
BufferedReader input
= new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
processList.add(line);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String line : processList) {
System.out.println(line);
}
}
}