java調用Linux的命令或者腳本
Runtime 類介紹:
每個 Java 應用程序都有一個 Runtime 類實例,使應用程序能夠與其運行的環境相連接。可以通過 getRuntime 方法獲取當前運行時。應用程序不能創建自己的 Runtime 類實例。
根據其API,通過Runtime重載的幾個方法可以來執行其shell命令
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)
在有指定環境和工作目錄的獨立進程中執行指定的字符串命令。
其中,其實cmdarray和command差不多,同時如果參數中如果沒有envp參數或設爲null,表示調用命令將在當前程序執行的環境中執行;
如果沒有dir參數或設爲null,表示調用命令將在當前程序執行的目錄中執行,因此調用到其他目錄中的文件和腳本最好使用絕對路徑。
cmdarray: 包含所調用命令及其參數的數組。
command: 一條指定的系統命令。
envp: 字符串數組,其中每個元素的環境變量的設置格式爲name=value;如果子進程應該繼承當前進程的環境,則該參數爲 null。
dir: 子進程的工作目錄;如果子進程應該繼承當前進程的工作目錄,則該參數爲 null。
爲了執行調用操作,JVM會啓一個Process,所以我們可以通過調用Process類的以下方法,得知調用操作是否正確執行
Process類介紹:
ProcessBuilder.start() 和 Runtime.exec 方法創建一個本機進程,並返回 Process 子類的一個實例,該實例可用來控制進程並獲得相關信息。
創建的子進程沒有自己的終端或控制檯。它的所有標準 io(即 stdin、stdout 和 stderr)操作都將通過三個流 (getOutputStream()、getInputStream() 和 getErrorStream()) 重定向到父進程。父進程使用這些流來提供到子進程的輸入和獲得從子進程的輸出。
abstract void destroy()
殺掉子進程。
abstract int exitValue()
返回子進程的出口值。
abstract InputStream getErrorStream()
獲取子進程的錯誤流。
abstract InputStream getInputStream()
獲取子進程的輸入流。
abstract OutputStream getOutputStream()
獲取子進程的輸出流。
abstract int waitFor()
導致當前線程等待,如有必要,一直要等到由該 Process 對象表示的進程已經終止。
實例代碼
public class Dotest {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long totalMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
System.out.println(maxMemory/1024/1024);
System.out.println(totalMemory/1024/1024);
System.out.println(freeMemory/1024/1024);
String cmd = ZhaoShell.Cmd("date");
System.out.println(cmd);
}
}
class ZhaoShell{
private static Runtime runtime;
static {
runtime=Runtime.getRuntime();
}
public static String Cmd(String cmd){
StringBuffer result = new StringBuffer();
Process exec =null;
try {
exec = runtime.exec(cmd);
//在調用時需要執行waitFor()函數,因爲shell進程是JAVA進程的子進程,JAVA作爲父進程需要等待子進程執行完畢。
exec.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String line = null;
while((line=input.readLine())!=null){
result.append(" "+line);
}
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
}