java调用shell
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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));
tErr=new Thread(){ //initialize thread tErr
String line;
int lineNumber=0;
public void run(){
try{
while((line=brErr.readLine())!=null){
System.out.println(lineNumber+". "+line); lineNumber++;
}
}
catch(IOException e){
e.printStackTrace();
}
}
};
// read buffer of parent process' input stream
final BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in)); final OutputStream outputStream = child.getOutputStream(); tIn=new Thread(){
String line;
public void run() {
try {
while (true) {
outputStream.write( (reader.readLine()+"\n").getBytes()); outputStream.flush();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
};
}
public void startIn(){ //start thread tIn
if(tIn!=null){
tIn.start();
}
}
public void startErr(){ //start thread tErr
if(tErr!=null){
tErr.start();
}
}
public void startOut(){ //start thread tOut
if(tOut!=null){
tOut.start();
}
}
public void interruptIn(){ //interrupt thread tIn
if(tIn!=null){
tIn.interrupt();
}
}
public void interruptErr(){ //interrupt thread tErr if(tErr!=null){
tErr.interrupt();
}
}
public void interruptOut(){ //interrupt thread tOut if(tOut!=null){
tOut.interrupt();
}
}
}