java 執行作業系統命令

qking93415981發表於2020-04-06

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

相關文章