用java調用shell,使用
Process p=Runtime.getRuntime().exec(String[] cmd);
Runtime.exec方法將產生一個本地的進程,并返回一個Process子類的實例,該實例可用于控制進程或取得進程的相關信息。
由于調用Runtime.exec方法所創建的子進程沒有自己的終端或控制臺,因此該子進程的標準IO(如stdin,stdou,stderr)都通過
p.getOutputStream(),
p.getInputStream(),
p.getErrorStream()
方法重定向給它的父進程了.用戶需要用這些stream來向 子進程輸入數據或獲取子進程的輸出。
例如:Runtime.getRuntime().exec("ls")
另外需要關心的是Runtime.getRuntime().exec()中產生停滯(阻塞,blocking)的問題?
這個是因為Runtime.getRuntime().exec()要自己去處理stdout和stderr的輸出,
就是說,執行的結果不知道是現有錯誤輸出(stderr),還是現有標準輸出(stdout)。
你無法判斷到底那個先輸出,所以可能無法讀取輸出,而一直阻塞。
例如:你先處理標準輸出(stdout),但是處理的結果是先有錯誤輸出(stderr),
一直在等錯誤輸出(stderr)被取走了,才到標準輸出(stdout),這樣就產生了阻塞。
解決辦法:
用兩個線程將標準輸出(stdout)和錯誤輸出(stderr)。
import java.util.*;
import java.io.*;
class StreamGobbler extends Thread
{
InputStream is;
String type;
StreamGobbler(InputStream is, String type)
{
this.is = is;
this.type = type;
}
public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
public class ExecRunner
{
public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("USAGE: java GoodWindowsExec <cmd>");
System.exit(1);
}
try
{
String osName = System.getProperty("os.name" );
String[] cmd = new String[3];
if( osName.equals( "Windows NT" ) )
{
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
else if( osName.equals( "Windows 95" ) )
{
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
} else {
StringTokenizer st = new StringTokenizer(command, " ");
cmd = new String[st.countTokens()];
int token = 0;
while (st.hasMoreTokens()) {
String tokenString = st.nextToken();
// System.out.println(tokenString);
cmd[token++] = tokenString;
}
}
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();淘寶女裝夏裝新款
// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
posted on 2011-05-16 16:04
墻頭草 閱讀(2641)
評論(0) 編輯 收藏