综合
首页 > > 正文

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


2017-08-24

原文之地: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#

本站为纯公益性文化知识交流分享网站,旨在促进文化知识学习、交流与传播。
此文章资料由本站转载于互联网,转载目的在于分享、传播文化知识。仅供学习、研究使用。版权归作者本人所有, 如果侵犯了您的版权和隐私权,请您将文章资料的网址发送到邮箱xuehuile@126.com,本站将马上删除。
违法、违规与不良信息投诉举报邮箱xuehuile@126.com,如果您发现不良信息,请您将文章资料的网址发送到邮箱,本站将马上删除。
此文章资料网址:http://m.xuehuile.com/blog/60bd75d9a2614e7683dee0fa438617e1.html