java调用'shell'脚本或'cmd'命令,并得到返回的结果集

ShellCmdLog.class中的代码:
public class ShellCmdLog extends Thread
{
private boolean bLog2Error; //是否打印错误Error标志
private InputStream ins; //待转换文件输入流

/**
* 设置是否打印错误Error,设置待转换文件的输入流
* @param is 待转换文件输入流
* @param flag 是否打印错误Error标志
*/
public ShellCmdLog(InputStream is, boolean flag)
{
super("ShellCmdStream" + (flag ? "-error" : "-out"));
bLog2Error = flag;
ins = is;
}

/**
* 执行转换线程
*/
public void run()
{
if (ins != null)
{
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader br = new BufferedReader(isr);
try
{
String line = null;
while ((line = br.readLine()) != null)
{
if (bLog2Error)
{
System.out.println("Shell_Err>" + line);
}
else
{
System.out.println("Shell_Out>" + line);
}
} //end of while(true)
}
catch (IOException ioe)
{
System.out.println("ShellCmdLog error:" + ioe);
}
finally
{
try
{
if (isr != null)
{
isr.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
try
{
if (br != null)
{
br.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}

// java调用shell脚本
String path="/zte/ippbxweb/util/zxecs_dbbackup.sh" ;//脚本位于服务器中的路径
String statement[] ={ "/bin/sh", path};
try {
Process process = Runtime.getRuntime().exec(statement);
InputStream in = process.getInputStream(); // 获取输入流
InputStream err = process.getErrorStream();// 获取错误流

ShellCmdLog sgStdout = new ShellCmdLog(in, false);
ShellCmdLog sgStderr = new ShellCmdLog(err, true);

sgStdout.start();
sgStderr.start();

final int result = process.waitFor();


// 为流读出捕获流设定的时间间隔。
Thread.sleep(100);

if (process != null) {
process.destroy();
}

// 集合读取线程
sgStdout.join();
sgStderr.join();


} catch (Exception e) {
e.toString();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值