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