java调用外部脚本或者程序,看了别人的代码,算是转载吧。

文中的注释纯属个人理解,有不当的地方勿喷,引用须谨慎!

有一个问题没搞好,当外部脚本引用其他脚本时,脚本中须用绝对路径,否则会将引用的脚本当命令执行,这样会提示 找不到命令,如果有谁知道怎么解决请一定要告诉我,大笑先口头感谢作为酬劳。



import java.lang.Runtime;
import java.lang.Process;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Exception;
import java.io.*;

public class RunCommand {
	/**
	 * @param args 
	 * @author yinduasan
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws IOException, InterruptedException {

		RunCommand javaExec = new RunCommand();
		String pig = "D:\\java\\pig.bat";
		javaExec.runProcess(pig,5);
		// if (args.length >= 1) {
		// javaExec.testProcess(args[0]);
		// }
		// else{
		// javaExec.testProcess(null);
		// }

	}

	/**
	 * @param userInputCmd 执行的命令
	 * @param tnum 等待时间
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public void runProcess(String userInputCmd,int tnum) throws IOException, InterruptedException {
		
		if (userInputCmd == null) {
			throw new NullPointerException("命令为空 ==!");
		} 
		if (!(new File(userInputCmd)).exists()) {
			throw new FileNotFoundException("找到不执行文件 ==!") ;
		}
		long sleepTime = tnum * 1000;
		ProcessBuilder builder = new ProcessBuilder();
		builder.redirectErrorStream(true); //输入流与错误流都可以用InputStreamReader获取
		builder.command(userInputCmd);
		Process process = builder.start() ;
		

//		process = Runtime.getRuntime().exec(userInputCmd);
		
		final InputStream ins = process.getInputStream() ;
		final StringBuilder sb = new StringBuilder();
		new Thread() {
			public void run() {
				BufferedReader br = new BufferedReader(new InputStreamReader(ins));
				try {
					String lineStr = null;
					while ((lineStr = br.readLine()) != null) {
						if (lineStr != null)
							sb.append(lineStr + "\r\n");
					}
				} catch (IOException e) {
					e.printStackTrace();
				} // end try
			} // end run
		}.start(); // end new Thread
		Thread.currentThread().sleep(sleepTime) ;
		String excep = sb.toString();
		process.getOutputStream().close();	//如果不关闭,有时候会造成IO阻塞,导致进程挂死
		if (process.waitFor() != 0) {//超时时间到进程仍没有返回结果, 0 为正常执行结束
			if (process.exitValue() != 0) {//外部程序执行结果, 0为正常结束
				throw new InterruptedException("执行命令被中断 ");
			}else {
				process.destroy();
				//截取最后输出的内容抛出
//				String excep = sb.toString();
//				System.out.println(excep);
				excep = excep.substring(excep.length() -2000, excep.length()) ;
				throw new InterruptedException(excep);
			}//end if process.exitValue
		}
		int exitValue = process.waitFor();
//		System.out.println(excep);
//		System.out.println(exitValue);
//		process.destroy();

	}
}


如果找到方法再补充。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值