java代码实现运行cmd命令

命令工厂:

public class CommandFactory {

    public static CommandLine createCommand(String command ,String[] parameter){
        if(null == command || "".equals(command)){
            System.out.println("the command must not null!") ;
            return null ;
        }
        return createJavaCommand(command, parameter) ;
    }
    
    private static CommandLine createJavaCommand(String command ,String[] parameter){
        //final String SPLIT = " " ;
        if(null == parameter || parameter.length < 1){
            return new CommandLine(command) ;
        } else {
            return new CommandLine(command,parameter);
        }
    }
}

 命令处理器:

public class CommandHandler {

   public static void excute(CommandLine command) throws IOException, InterruptedException {

        if (null == command || "".equals(command)) {
            System.out.println("the parameter[command] must not null!");
            return;
        }
        try {
            System.out.println("execute command start:" + command) ;
            Runtime runtime = Runtime.getRuntime();
            Process pro = runtime.exec(command.toString());
            SimpleThreadPool queue = SimpleThreadPool.getWorkQueue(4) ;
            CommandStream commandStream = new CommandStream();
            commandStream.setCharset("gbk") ;
            commandStream.setCommandLine(command) ;
            commandStream.setIs(pro.getInputStream()) ;
            commandStream.setType("IN") ;
            queue.postCommandStream(commandStream) ;
            commandStream = new CommandStream();
            commandStream.setCharset("gbk") ;
            commandStream.setCommandLine(command) ;
            commandStream.setIs(pro.getErrorStream()) ;
            commandStream.setType("ERROR") ;
            queue.postCommandStream(commandStream) ;
            int exitVal = pro.waitFor() ;
            System.out.println("execute command end:" + command + " exit value:" +exitVal) ;
        } catch (IOException e) {
            e.printStackTrace() ;
            throw e ;
        } catch (InterruptedException e) {
            e.printStackTrace() ;
            throw e ;
        }
    }


}

 命令行:

public class CommandLine {

    private String command ;
    private String[] parameters ;
    /**
     * @param command
     * @param parameters
     */
    public CommandLine(String command, String[] parameters) {
        if(command == null || "".equals(command)) {
            throw new IllegalArgumentException("the parameter[command] must not null!") ;
        }
        if(parameters == null ) {
            throw new IllegalArgumentException("the parameter[parameters] must not null!") ;
        }
        this.command = command;
        this.parameters = parameters;
    }
 
    /**
     * @param command2
     */
    public CommandLine(String command) {
        this.command = command ;
        }

    public String toString() {
        StringBuilder sb = new StringBuilder() ;
        final String split = " " ;
        sb.append(command + split) ;
        for(String parameter : parameters) {
            sb.append(parameter+split) ;
        }
        return sb.toString() ;
    }
}

 命令流:

public class CommandStream {
    /**
     * @return the commandLine
     */
    public CommandLine getCommandLine() {
        return commandLine;
    }
    /**
     * @param commandLine the commandLine to set
     */
    public void setCommandLine(CommandLine commandLine) {
        this.commandLine = commandLine;
    }
    private CommandLine commandLine ;
    private String type ;
    /**
     * @return the type
     */
    public String getType() {
        return type;
    }
    /**
     * @param type the type to set
     */
    public void setType(String type) {
        this.type = type;
    }
    private InputStream is;
    private String charset = "gbk" ;
    /**
     * @return the is
     */
    public InputStream getIs() {
        return is;
    }
    /**
     * @param is the is to set
     */
    public void setIs(InputStream is) {
        this.is = is;
    }
    /**
     * @return the charset
     */
    public String getCharset() {
        return charset;
    }
    /**
     * @param charset the charset to set
     */
    public void setCharset(String charset) {
        this.charset = charset;
    }
  

}

 命令处理器:

public class CommandStreamHandler extends Thread{

    private SimpleThreadPool queue ;
    
    private volatile boolean run = true ;
    public void run(){
        while (run) {
            CommandStream commandStream = queue.selectCommandStream();
         if (null != commandStream) {
          handleEvent(commandStream);
         }
        }
    }

    /**
     * @param commandStream
     * @Description:
     */
    private void handleEvent(CommandStream commandStream) {
        InputStreamReader isr = null ;;
        BufferedReader br = null;
        try {
            isr = new InputStreamReader(commandStream.getIs(),commandStream.getCharset());
            br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(commandStream.getType()+">>>>>>>>>>>>>>>>>" + line) ;
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }finally {
            if(br != null) {
                try {
                    br.close() ;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param workQueue
     * @Description:
     */
    public void setQueue(SimpleThreadPool workQueue) {
        this.queue = workQueue ;
        
    }
    
    public void toStop(){
        this.run = false ;
    }
}

 线程池:

public class SimpleThreadPool {

    /**
     * 默认的最大任务数。
     */
    private static final int DEFAULT_MAX_TASK_NUM = 5;

    /**
     * 最大任务数。仅对会话任务限制。
     */
    private  int maxTaskNum = DEFAULT_MAX_TASK_NUM;
    
    public  LinkedList<CommandStream> commandQueue = new LinkedList<CommandStream>();

    /**
     * 队列
     */
    public  CommandStreamHandler[] handlerQueue ;
    
    private static SimpleThreadPool  instance ;

    public static SimpleThreadPool getWorkQueue(int number){
        if(instance == null) {
            instance = new SimpleThreadPool(number);
        }
        return instance ;
    }
    
    private SimpleThreadPool(int number){
        start(number) ;
    }
    
    private void start(int number) {
        handlerQueue = new CommandStreamHandler[number];
        for (int i = 0; i < number; i++) {
            handlerQueue[i] = new CommandStreamHandler();
            handlerQueue[i].setQueue(this);
            handlerQueue[i].setContextClassLoader(Thread.currentThread()
           .getContextClassLoader());
         //
            handlerQueue[i].setDaemon(true) ;
            handlerQueue[i].start();
        }
    }

    /**
     * 任务入队
     * 
     * @param commandStream
     * @return false入队失败
     */
    public  boolean postCommandStream(CommandStream commandStream) {

        synchronized (commandQueue) {
            // 当排队任务超过最大任务数时,禁止会话任务加入
            if (commandQueue.size() > maxTaskNum) {
                return false;
            }
 
            // 加入任务
            commandQueue.add(commandStream);

            // 唤醒一个等待的处理线程
            commandQueue.notify();

        }

        return true;
    }

    /**
     * 取得一个任务。当队列为空时wait。
     * 
     * @return
     */
    public  CommandStream selectCommandStream() {
        CommandStream handler = null;
        synchronized (commandQueue) {
            while (commandQueue.size() == 0) {
                try {
                    commandQueue.wait();
                } catch (InterruptedException e) {
                    return null;
                }
            }
            if (commandQueue.size() > 0) {
                
                handler = commandQueue.remove();
            } else {
                handler = null;
            }
        }
        return handler;
    }

    public  int getMaxTaskNum() {
        return maxTaskNum;
    }

    
    public void stop() {
        for(CommandStreamHandler handler :   handlerQueue) {
            handler.toStop() ;
        }
    }
}
 

你可能感兴趣的:(java,thread)