java 执行操作系统命令

Java执行命令工具
本文介绍了一个Java工具类,用于执行操作系统命令并获取输出信息。该工具支持超时判断及错误处理,通过创建子进程的方式执行命令,并利用多线程读取标准输出和错误输出。

  java 执行操作系统命令,包括输出信息的获取和超时判断 

package com.ctoc.web.msgtools.smtplog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class CommandRunner {
    
private StringBuilder rsBuilder;
    
private StringBuilder errBuilder;
    
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
    
private long timeout = 1000 * 60 * 5;//5分钟
    private Process p = null;
    
private String command;


    
public String runCommand(String command) throws CommandException {
        
this.command = command;

        
if (command == null || command.trim().length() == 0) {
            
throw new CommandException("command is null or empty!");
        }

        
// Start up the process
        try {
            p 
= Runtime.getRuntime().exec(command);
        } 
catch (IOException e) {
            e.printStackTrace();
            
throw new CommandException(e.getMessage());
        }

        
this.errBuilder = new StringBuilder();
        
this.rsBuilder = new StringBuilder();
        
        Thread tIn  
=   new  CommandOutputStreamReadThread( p.getInputStream(),false);
        Thread tErr  
=   new  CommandOutputStreamReadThread( p.getErrorStream(),true);
        
        
//超时检查
        Thread tCheck = new TimeOutCheckThread();
        
        tIn.start();
        tErr.start();
        tCheck.start();
        
        
// Wait for it to finish running
        try {
            p.waitFor();
            tIn.join();
            tErr.join();
            
            tCheck.stop();
        
        } 
catch (InterruptedException ie) {

            System.out.println(ie);
        }
        
// Check the return code

        
// ok=0;
        int ret = p.exitValue();
        
if(ret != 0){
            
throw new CommandException("execute fail:" + command 
                                        
+LINE_SEPARATOR + 
                                        
this.errBuilder.toString());
        }
        
return rsBuilder.toString();
    }

    
public void stopRun(){
        
if(p != null){
            System.err.println(
"destroy process of command:" + command);
            p.destroy();
        }
    }
    
    
/**
     * 命令输出结果获取线程
     * 
@author qking
     *
     
*/
    
class CommandOutputStreamReadThread extends Thread {
        
private InputStream is;
        
private boolean errorStream;

        CommandOutputStreamReadThread(InputStream is, 
boolean errorStream) {
            
this.is = is;
            
this.errorStream = errorStream;
        }

        @Override
        
public void run() {
            StringBuilder sb;
            
if(errorStream){
                sb 
= errBuilder;
            }
else{
                sb 
= rsBuilder;
            }

            InputStreamReader isr 
= new InputStreamReader(is);
            BufferedReader reader 
= new BufferedReader(isr);
            String s;
            
try {
                
while ((s = reader.readLine()) != null) {
                    
if (s.length() != 0) {
                        sb.append(s);
                        sb.append(LINE_SEPARATOR);
                        
try {
                            Thread.sleep(
10);
                        } 
catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            } 
catch (IOException ex) {
                ex.printStackTrace();
            }

        }

    }

    
/**
     * 检查操作超时线程
     * 
@author qking
     *
     
*/
    
class TimeOutCheckThread extends Thread{

        @Override
        
public void run() {
            
//-1时不进行超时判断
            if(timeout == -1){
                
return;
            }
            
try{
                
this.sleep(timeout);
            }
catch(InterruptedException ie){
                ie.printStackTrace();
            }
            
            stopRun();
        }
        
        
    }
    
    
public static void main(String[] args) throws Exception {
        CommandRunner cr 
= new CommandRunner();

        System.out.println(cr.runCommand(
"test.bat"));

    }

    
public long getTimeout() {
        
return timeout;
    }

    
public void setTimeout(long timeout) {
        
this.timeout = timeout;
    }
}
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值