Java执行shell脚本文件

Java调用shell脚本的问题,曾在之前的开发中遇到过,虽然调用方法很简单(貌似当时花了我蛮长时间),还是做个记录吧(年纪大了,易忘哈)~


配置文件中配置shell脚本文件执行命令,如:

sg_sam_command_model=sh ./sam_model.sh

java中获取配置项:

public boolean model(){
		try {
			String command = SGConfig.getInstance().getItem("sg_sam_command_model");
			ScriptUtil.executeScript(command);
			Thread.sleep(50000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}


java执行脚本:

public static void executeScript(String command){
		Process pcs = null ;
		InputStreamReader is = null;
		LineNumberReader in = null;
		try{
			Runtime rt = Runtime.getRuntime();
		    pcs = rt.exec(command);
		    is = new InputStreamReader(pcs.getInputStream());  
            in = new LineNumberReader(is);  
            String line;  
            pcs.waitFor();
            while ((line = in.readLine()) != null) {
                System.out.println(line);  
            }
		} catch(InterruptedException e){
			System.err.println("processes was interrupted");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(pcs != null){
				pcs.destroy();
			}
		}
	}


ok,搞定收工!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值