标题: Java执行shell [打印本页] 作者: nkmaniac 时间: 2007-05-12 11:43 标题: Java执行shell CODE: jShell.java
----------------------------------------------------------------------------------
/*
* jShell.java
* class jShell is used for executing shell command
* USAGE:
* jShell obj=new jShell(shellCommand);
* obj.startErr();
* obj.startOut();
* obj.startIn();
* You can Interupt I/O thread when nessasary:
* obj.interruptErr();
* obj.interruptOut();
* obj.interruptIn();
*
* BY Ahui Wang Nankai U. 2007-05-12
*/
import java.io.*;
public class jShell {
Thread tIn; //handle input of child process
Thread tOut;//handle output of child process
Thread tErr;//handle error output of child process
public jShell(String shellCommand){
Process child=null; //child process
try{
child=Runtime.getRuntime().exec(shellCommand);
}
catch(IOException e){
e.printStackTrace();
}
if(child==null){
return;
}
final InputStream inputStream=child.getInputStream();
final BufferedReader brOut=
new BufferedReader(new InputStreamReader(inputStream));
tOut=new Thread(){ //initialize thread tOut
String line;
int lineNumber=0;
public void run(){
try{
while((line=brOut.readLine())!=null){
System.out.println(lineNumber+". "+line);
lineNumber++;
}
}
catch(IOException e){
e.printStackTrace();
}
}
};
final InputStream errorStream=child.getErrorStream();
final BufferedReader brErr=
new BufferedReader(new InputStreamReader(errorStream));