`

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程序执行CMD命令代码实现

    Java程序是如何执行CMD命令的,就是需要RunTime、Process类而已。 具体代码在文档中

    java 以管理员身份调用cmd 需要用到的文件

    下面我们将详细讲解如何在Java中以管理员权限运行CMD命令,以及`nircmd.exe`在这个过程中的作用。 `nircmd.exe`是一个强大的命令行工具,由NirSoft公司开发,它提供了一系列实用的命令,可以帮助我们执行一些...

    java中如何调cmd命令

    本文将详细介绍如何利用Java的`Runtime.getRuntime().exec()`方法来实现对CMD命令的调用,并通过具体的例子来帮助读者理解和掌握这一技术。 #### 1. 基本原理 `java.lang.Runtime`类提供了运行时环境的表示,通过...

    java 调用 windows cmd 命令

    总结,通过Java调用Windows CMD命令,我们可以方便地执行系统级任务,实现与操作系统的交互。`FileProcessInShell.java`可能就是这样一个例子,它演示了如何在Java程序中执行和处理CMD命令的输出。在实际开发中,...

    java运行windows的cmd命令简单代码

    通过Java运行CMD命令,可以实现自动化任务、远程控制、系统监控等多种功能,尤其是在开发跨平台的应用时,这种能力尤为关键。了解如何正确地调用和控制操作系统命令是Java开发者必备的技能之一。

    java代码-//运行cmd命令并返回结果

    在Java编程中,有时我们需要执行操作系统级别的命令,例如运行`cmd`命令,获取命令的输出结果,这通常涉及到进程的创建和管理。本篇将详细讲解如何在Java中实现这一功能,以及涉及的相关知识点。 首先,Java提供了...

    java代码快捷编译运行工具

    Java代码快捷编译运行工具则提供了图形用户界面(GUI),用户可以直接在该界面上打开.java文件,点击编译按钮即可自动完成编译过程,无需手动输入命令。同时,编译成功后,工具还会提供运行按钮,一键启动程序,显示...

    java javascript 调用命令行 cmd

    在IT领域,有时候我们需要在Java或JavaScript代码中执行操作系统级别的命令,例如运行系统脚本、管理文件、控制进程等。这种需求通常通过调用命令行(CMD)来实现。本文将详细探讨如何在Java和JavaScript中调用...

    读取指定文件每行并运行cmd命令

    标题 "读取指定文件每行并运行cmd命令" 涉及的核心知识点是通过编程方式读取文本文件的每一行内容,并将这些内容作为命令在命令行(CMD)环境中执行。这种操作通常在自动化脚本或者系统管理任务中非常有用。下面我们...

    给cmd穿曾java外衣

    这两个类提供了与操作系统进行交互的能力,可以用来启动外部进程,例如运行CMD命令。例如,我们可以使用`Runtime.getRuntime().exec(command)`或者`ProcessBuilder(commands).start()`来执行CMD命令。这里的`command...

    cmd命令加密工具

    CMD命令加密工具是专门用于在命令行环境下对数据进行加密的实用程序,它允许用户安全地存储和传输敏感信息。在本文中,我们将深入探讨CMD命令加密的相关知识点,以及如何使用CMD加密.exe这样的工具。 首先,了解CMD...

    dos命令测试java jar文件 命令行下运行JUnit测试 命令运行java

    这里我们主要探讨如何使用DOS命令来测试Java JAR文件,以及如何在命令行下运行JUnit测试。这是一项基础但至关重要的技能,因为通过命令行工具可以高效地自动化测试和调试代码。 首先,让我们了解Java JAR文件。JAR...

    java调用cmd创建目录和复制文件

    - 操作系统兼容性:上述代码是针对Windows系统的,如果要在其他操作系统(如Linux或MacOS)上运行,需要使用相应的命令(如`mkdir`和`cp`)。 - 错误处理:务必捕获并处理可能出现的异常,如文件不存在、权限不足等...

    cmd中java命令出现找不到主类的错误处理

    ### 关于CMD中Java命令出现“找不到主类”的错误处理 #### 一、问题概述 在使用命令提示符(cmd)执行Java程序时,有时会遇到“找不到或无法加载主类”这样的错误信息。这种情况通常发生在Java环境配置不正确或者...

    统计代码行数的cmd小工具(附源码)

    总的来说,"统计代码行数的cmd小工具"是软件开发过程中的一个辅助工具,它利用C++的强大功能提供了快速、灵活的代码统计能力。通过命令行界面,开发者可以方便地集成到日常开发环境中,更好地管理和监控项目的进度。...

    Windows系统中Java调用cmd命令及执行exe程序的方法

    ### Java调用cmd命令 1. **使用Runtime类**: Java中可以使用`Runtime`类来获取Java程序的运行时对象。通过运行时对象,可以使用`exec()`方法来执行系统命令。 2. **命令格式**: 在Java中执行cmd命令时,常用的...

    CMD命令速查手册.docx

    ### CMD命令速查手册知识点详解 #### 一、概述 《CMD命令速查手册》是一份详尽的文档,旨在帮助用户快速掌握Windows操作系统中CMD(命令提示符)下的各种命令及其用法。CMD作为Windows操作系统的一个重要组成部分,...

    在DOS环境下(cmd)编译及运行java程序教程

    2. **编译Java源代码**:Java源代码通常是`.java`文件,使用`javac`命令进行编译。例如,如果你有一个名为`HelloWorld.java`的文件,你将在命令行中输入`javac HelloWorld.java`。这将会生成一个对应的`.class`文件...

Global site tag (gtag.js) - Google Analytics