综合
首页 > 学术社区 > 文章 > 正文

Java中执行Shell(.sh)和windows批量处理(.bat)


评论(0)|2017-08-24|发布:andazon |收藏

原文之地:http://blog.csdn.net/Nicolas_Yang/archive/2008/12/12/3504480.aspx

【JAVA 中执行Shell】


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();
}
}

}

系统分类:编程语言 >> C#

评论
请登录再发布评论,所有评论仅代表网友意见,本网站保持中立