作為一個Java開發人員,有些常用的Linux命令必須掌握。即時平時開發過程中不使用Linux(Unix)或者mac系統,也需要熟練掌握Linux命令。因為很多服務器上都是Linux系統。所以,要和伺服器機器互動,就要通過shell命令。本文為大家分享的就是java程式中怎麼呼叫linux命令。
Java呼叫shell
Java語言以其跨平臺性和簡易性而著稱,在Java裡面的lang包裡(ime)提供了一個允許Java程式與該程式所執行的環境互動的介面,這就是Runtime類,在Runtime類裡提供了獲取當前執行環境的介面。
其中的exec函式返回一個執行shell命令的子程序。exec函式的.具體實現形式有以下幾種:
public Process exec(String command) throws IOException
public Process exec(String command,String[] envp) throws
IOException
public Process exec(String command,String[] envp,File dir) throws
IOException
public Process exec(String[] cmdarray) throws IOException
public Process exec(String[] cmdarray, String[] envp) throws
IOException
public Process exec(String[] cmdarray, String[] envp,File dir)
throws IOException
我們在這裡主要用到的是第一個和第四個函式,具體方法很簡單,就是在exec函式中傳遞一個代表命令的字串。exec函式返回的是一個Process型別的類的例項。Process類主要用來控制程序,獲取程序資訊等作用。(具體資訊及其用法請參看Java doc)。
1)執行簡單的命令的方法:
程式碼如下:
try
String commands = "ls -l";
Process process = untime() (commands);
// for showing the info on screen
InputStreamReader ir=new
InputStreamReader(nputStream());
BufferedReader input = new BufferedReader (ir);
String line;
while ((line = Line ()) != null){
tln(line);
}//end try
catch (ception e){
tln ("IOException " + essage());
} 上面的程式碼首先是聲明瞭一個代表命令的字串commands,它代表了ls -l
這個命令。之後我們用untime()(commands)來生成一個子程序來執行這個命令,如果這句話執行成功,則命令 ls -l 執行成功(由於沒有讓它顯示,不會顯示ls -l
的結果)。後面的流操作則是獲取程序的流資訊,並把它們一行行輸出到螢幕。2)執行帶有引數的命令(尤其是引數需要用引號的)時則需要用String的陣列來表示整個命令,而且要用轉義符把引號的特殊含義去除,例如我們要執行find / -name "*mysql*" -print 時,用如下程式碼
try
String[] commands = new
String[]{"find",".","-name","*mysql*","-print"};
Process process = untime() (commands);
InputStreamReader ir=new
InputStreamReader(nputStream());
BufferedReader input = new BufferedReader (ir);
String line;
while ((line = Line ()) != null){
tln(line);
}//end try
catch (ception e){
tln ("IOException " + essage());
Java 可以通過 Runtime 呼叫Linux命令,形式如下:
untime()(command)
但是這樣執行時沒有任何輸出,因為呼叫 方法將產生一個本地的程序,並返回一個Process子類的例項(注意:untime()(command)返回的是一個Process類的例項)該例項可用於控制程序或取得程序的相關資訊。
由於呼叫 方法所建立的子程序沒有自己的終端或控制檯,因此該子程序的標準IO(如stdin,stdou,stderr)都通過 utputStream(),nputStream(), rrorStream() 方法重定向給它的父程序了。
使用者需要用這些stream來向子程序輸入資料或獲取子程序的輸出,下面的程式碼可以取到 linux 命令的執行結果:
try {
String[] cmd = new String[]{”/bin/sh”, “-c”, ” ls “};
Process ps = untime()(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(nputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = Line()) != null) {
nd(line)nd(”n”);
}
String result = ring();
tln(result);
} catch (Exception e) {
tStackTrace();
}