java中调用linux命令或者脚本


       系统中需要实现在网页上点击按钮从而自动更新网站版本,而更新网站版本需要在服务器上执行一系列的操作,将一系列的命令写入shell脚本中,在java后台中调用并执行该脚本,就可以实现需求功能。

      进入正题,在java中调用一个shell脚本,例如调用“/home/tomcat/bin/start.sh”这个脚本,代码如下:


import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;


public class test{
/** 
     * 运行shell脚本 
     * @param shell 需要运行的shell脚本 
     */  
     public static void execShell(String shell){
  
        try {  
            Runtime rt = Runtime.getRuntime();  
            rt.exec(shell);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
     }  
/** 
     * 运行shell 
     *  
     * @param shStr 
     *            需要执行的shell 
     * @return 
     * @throws IOException 
     */  
    public static List runShell(String shStr) throws Exception {  
        List<String> strList = new ArrayList();  
  
        Process process;  
        process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null);  
        //process = Runtime.getRuntime().exec(shStr); 
        InputStreamReader ir = new InputStreamReader(process  
                .getInputStream());  
        LineNumberReader input = new LineNumberReader(ir);  
        String line;  
        process.waitFor();  
        while ((line = input.readLine()) != null){  
            System.out.println(line);
        	strList.add(line);  
        }  
          
        return strList;  
    }
    public static void main(String []arge)throws Exception {
    	
    	test t=new test();
    	t.runShell("/home/ubuntu/soft/tomcat/bin/startup.sh")
    }
    
    
    
    
    
}

 注意:执行的脚本跟java进程在一个进程中。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值