`

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运行windows的cmd命令简单代码

    主要介绍了java运行windows的cmd命令简单代码,有需要的朋友可以参考一下

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

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

    使用C++语言实现基于JVMTI机制的 JAVA 代码 加密保护工具

    打开windows命令行(运行=&gt;cmd=&gt;回车),在命令行中 进入 EncryptJar目录 2.执行 java -jar encrypt.jar 3.输入h,然后回车,可以看到帮助菜单 4.输入3,然后按回车键,进入加入jar文件功能 5.输入要加密的jar文件的...

    sudo提权自动输入密码--java执行交互式命令

    参考了java版的expect4j,expectj的原理,进行了极大的简化,可完成基本的功能: 1,运行java代码,执行交互式命令 2,sudo提权,自动输入密码(echo "password" | sudo -S mkdir /opt/test)

    java实现万年历详细jar包运行教程

    本例子用cmd命令运行该项目,方便快捷,代码多行注释,方便阅读理解,包含运行的cmd命令。

    将java程序打成jar包在cmd命令行下执行的方法

    主要给大家介绍了关于将java程序打成jar包在cmd命令行下执行的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

    java mysql代码自动生成工具(dao接口 , xml , model)

    2.在当前目录下运行cmd , 在命令框中执行 指令.txt 文档中的命令 3.执行成功后 就可以在你配置的生成文件存放路径中 找到你想要的java代码类和xml 文件 注意: 1.库表一定要配置正确 2.数据库字段命名建议规范(全大写...

    java基础学习笔记 java整合技术 java工具类.rar

    启动dos窗口 win+R 输入cmd 输入jshell 直接可以敲java代码 3.1:JAVA开发工具包 JRE、JDK、JVM JRE是java运行环境,运行java所必需的文件 JDK是开发工具包,增加编译器和调试器等用于程序开发的文件 JVM是java的...

    java环境搭建文档

    windows开始 -&gt; 运行 -&gt; cmd -&gt; 进入msdos命令窗体 java java执行命令 使用Java虚拟机JVM运行编译后的字节码文件 javac java编译命令 将java原代码文件.java编译成字节码文件.class java -version 显示当前...

    Java商城网站系统设计与实现基于java+springboot+vue开发的电子商城网站-毕业设计-课程设计.zip

    Java商城网站系统设计与实现基于java+springboot+vue开发的电子商城网站-毕业设计-课程...cmd命令进入web目录下,安装依赖,执行: npm install 运行项目 npm run dev 在浏览器输入: http://localhost:3000 即可预览

    反编译JAVA的class文件的简单方法,附"文件分割器"完整源代码

    以我的为例,操作步骤如下: 我将class文件FileSa.class和jad放在E盘根目录下; 打开“命令提示符”快捷键操作:WIN+R; 再依次如下几步: cmd 回车;... 注3:要运行,在命令提示符中输入java FileSa即可

    java开发项目图书管理系统源代码web课程设计, springboot+mybatis

    管理员对图书信息的增删改查、查看读者、查看...如果不想用IDE打开项目而是想直接运行的朋友们,在目录下打开cmd键入mvn package命令,然后在target/目录下会生成对应的jar包,在cmd用“java -jar jar包名”运行即可

    java sqlserver代码自动生成工具(dao接口 , xml , model)

    使用步骤: ...2.在当前目录下运行cmd , 在命令框中执行 指令.txt 文档中的命令 3.执行成功后 就可以在你配置的生成文件存放路径中 找到你想要的java代码类和xml 文件 注意: 1.库表一定要配置正确

    查看apk文件原码工具及用法说明

    二、从解压缩的文件夹中取出classes.dex文件并放到dex2jar.bat所在目录,运行cmd命令, 进入dex2jar.bat所在的目录,输入dex2jar.bat classes.dex即可生成classes.dex.dex2jar.jar文件 三、用jd-gui工具打开classes...

    corejava基础重要知识点总结

    jre:当一个电脑上面安装jre之后 只能运行java代码 2:设置环境变量 (环境变量可以不设置 为了简化开发流程 提高开发效率) 给谁使用 作用 PATH: 操作系统 让操作系统更加快捷的找到一个文件/命令 PATH=C:\...

    ARSE编辑器

    android反编译,android的apk反编译工具,适合大家一起学,可以把android生成的apk转为java代码,希望对大家有用。 一、更改apk文件的后缀名,如:LianyunHelper3.0.11.apk改成LianyunHelper3.0.11.zip 二、用zip解...

    Android反编译工具

    android反编译,android的apk反编译工具,适合大家一起学,可以把android生成的apk转为java代码,希望对大家有用。 一、更改apk文件的后缀名,如:aa.apk改成aa.zip 二、用zip解压缩aa.zip文件 三、从解压缩的文件夹中...

    JAVA项目过程

    2、在cmd命令窗口输入services.msc,找到MYSQL服务选项,如果没有启动则需要手动启动它。 3、进入navicatformysql界面,进行数据库连接测试,测试成功后创建数据库(在powerdesigner中生成的可运行sql脚本)。 4、...

    java cmd compile and run batch file:批处理文件,用于通过命令提示符进行编译(javac)和运行Java-开源

    任何时候只要您想编写简单的程序来测试代码或进行其他操作,请使用我制作的这些批处理文件。 它们比打开IDE并输入所有内容进行测试要快得多。 然后,批处理文件“ RunJavaCode”创建一个.class文件(字节码),然后...

Global site tag (gtag.js) - Google Analytics