Java 可以通過 Runtime 調用Linux命令,形式如下:
Runtime.getRuntime().exec(command)
但是這樣執行時沒有任何輸出,因為調用 Runtime.exec 方法將產生一個本地的進程,並返回一個Process子類的實例
(注意:Runtime.getRuntime().exec(command)返回的是一個Process類的實例)該實例可用於控制進程或取得進程的相關信息。
由於調用 Runtime.exec 方法所創建的子進程沒有自己的終端或控制台,因此該子進程的標准IO(如stdin,stdou,stderr)都通過 Process.getOutputStream(),Process.getInputStream(), Process.getErrorStream() 方法重定向給它的父進程了。
用戶需要用這些stream來向子進程輸入數據或獲取子進程的輸出,下面的代碼可以取到 linux 命令的執行結果:
try {
String[] cmd = new String[]{”/bin/sh”, “-c”, ” ls “};
Process ps = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append(”\n”);
}
String result = sb.toString();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
package com.cisco.learning;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class Ys {
public static void main(String[] args) throws IOException {
Process exec = Runtime.getRuntime().exec("notepad");
InputStream inputStream = exec.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder(10);
try {
String tmp;
while ((tmp = bufferedReader.readLine()) != null) {
stringBuilder.append(tmp);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
bufferedReader.close();
}
System.out.println(stringBuilder.toString());
}
}
package com.cisco.learning;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class Ys {
public static void main(String[] args) throws IOException {
Process exec = Runtime.getRuntime().exec("notepad");
InputStream inputStream = exec.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder(10);
try {
String tmp;
while ((tmp = bufferedReader.readLine()) != null) {
stringBuilder.append(tmp);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
bufferedReader.close();
}
System.out.println(stringBuilder.toString());
}
}