手机版
你好,游客 登录 注册
背景:
阅读新闻

Java运行系统命令

[日期:2013-05-02] 来源:Linux社区  作者:sheismylife [字体:大 中 小]

前面写过一个版本的Java代码用来调用linux shell脚本,原文如下:http://www.linuxidc.com/Linux/2013-05/83739.htm

不过没有试过Windows下运行,试了一下,还是不错的,把代码做了一些调整,封装成对象,这样更方便多线程下调用,不用担心静态变量互相干扰的问题。

先看一下怎么用:

    public static void main(String[] args) {
        try {
            Command command = new Command();
            CommandResult result1 = command.exec("net stop nginx", 20000);
            System.out.println("command executiion succeeds: " + result1.getOutput());
            CommandResult result2 = command.exec("net start nginx", 20000);
            System.out.println("command executiion succeeds: " + result2.getOutput());
        } catch (CommandError ex) {
            System.out.println("command execution failed: " + ex.getMessage());
        }
    }

由此可见,有三个类:Command, CommandResult和CommandError。

当命令不能运行,将会抛出CommandError异常对象。如果命令能够运行,不管是否成功或者失败,都返回CommandResult对象,里面有两个属性output和error,包含了执行成功的消息和错误消息。

CommandError.java代码:

package command;

/**
 *
 * @author shu6889
 */
public class CommandError extends Exception {

    /**
    * Creates a new instance of
    * <code>CommandError</code> without detail message.
    */
    public CommandError() {
    }

    /**
    * Constructs an instance of
    * <code>CommandError</code> with the specified detail message.
    *
    * @param msg the detail message.
    */
    public CommandError(String msg) {
        super(msg);
    }
   
    public CommandError(Throwable ex) {
        super(ex);
    }
}

CommandResult.java代码

package command;


/**
* Describe class CommandResult here.
*
*/
public class CommandResult {
 public static final int EXIT_VALUE_TIMEOUT=-1;
   
    private String output;

    void setOutput(String error) {
        output=error;
    }

    public String getOutput(){
        return output;
    }

    int exitValue;

    void setExitValue(int value) {
        exitValue=value;
    }

    int getExitValue(){
        return exitValue;
    }

    private String error;

    /**
    * @return the error
    */
    public String getError() {
        return error;
    }

    /**
    * @param error the error to set
    */
    public void setError(String error) {
        this.error = error;
    }
}

linux
相关资讯       系统命令 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款