java-程序运行外部的exe程序

来源:互联网 发布:美丽港软件下载 编辑:程序博客网 时间:2024/05/18 19:40

使用java程序来运行外部的exe程序

java提供了调用外部程序的api

 

见实例:

String[] arguments={"keytool","-gentool","-alias","server","-keystore","server.keystore"};

Process process=Runtime.getRuntime().exec(arguments);

 

 

下面包装一个 运行外部程序的类  获得输入的命令 执行 输出

 

 

 

 public class CommandRunner extends Thread {


        // Private instance variables

    private String[] arguments;
    private StringBuffer outBuf = new StringBuffer();
    private Process process;
    private boolean includeOutputOnException;

    /**
     * Constructor. The first argument supplied must be the name of the command
     * (if it is on the system path) or the full path the command. Any command
     * arguments should be supplied as further elements.
     *
     * @param arguments
     */
    public CommandRunner(String[] arguments) {
        this.arguments = arguments;
    }

    /**
     * Constructor. The first argument supplied must be the name of the command
     * (if it is on the system path) or the full path the command. Any command
     * arguments should be supplied as further elements.
     *
     * @param arguments
     */
    public CommandRunner(Vector arguments) {
        this.arguments = new String[arguments.size()];
        arguments.copyInto(this.arguments);
    }

    /**
     * Get the output of the command.
     *
     * @return output
     */
    public String getOutput() {
        return outBuf.toString();
    }

    /**
     * Run the command. Any output will then be availabie from
     * {@link #getOutput()}. An exception will be thrown if the command returns
     * a non-zero exit value.
     *
     * @throws Exception if any error occurs running the command.
     */
    public void runCommand() throws Exception {
        try {

                            
                StringBuffer debug = new StringBuffer("Running command '");
                for (int i = 0; i < arguments.length; i++) {
                    if (i > 0) {
                        debug.append(" ");
                    }
                    debug.append("/"");
                    debug.append(arguments[i]);
                    debug.append("/"");
                }
   
                if(log.isDebugEnabled()) {
                 log.debug(debug.toString());
                }
                

            process = Runtime.getRuntime().exec(arguments);
            InputStream in = process.getInputStream();
            start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                
                synchronized (outBuf) {
                    if (outBuf.length() > 0) {
                        outBuf.append("/n");
                    }
                    outBuf.append(line);
                }
            }
            process.waitFor();
            if (process.exitValue() != 0) {
                log.error("Command '" + arguments[0] + "' failed with exit code " + process.exitValue());
                log.error("Start of command output ---->");
                log.error(outBuf.toString());
                log.error("<---- End of command output");
                throw new Exception("Command returned exit code " + process.exitValue() + ". "
                                + (includeOutputOnException ? outBuf.toString() : "Check the logs for more detail."));
            }
        } finally {
        }
    }

    /**
     * Set whther the output should be included in the exception text should an
     * error occur.
     *
     * @param includeOutputOnException include output on exception
     */
    public void setIncludeOutputOnException(boolean includeOutputOnException) {
        this.includeOutputOnException = includeOutputOnException;

    }

    public void run() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                
                synchronized (outBuf) {
                    if (outBuf.length() > 0) {
                        outBuf.append("/n");
                    }
                    outBuf.append(line);
                }
            }
        } catch (IOException ioe) {
        }
    }
}

 

 

 

这里包装一个类 用于执行外部程序 并获得执行结果到outBuf之中

 

注意:取得退出结果(exitValue())的时候,必须等待被调用的程序执行完毕之后才可以取得结果,使用process.waitFor() 方法来等待,该方法阻塞了当前调用进程

并等待被调用进程执行完毕返回退出结果。

 

取得执行的结果和错误 ErrorStream,使用getInputstream即可 在程序运行后即可取得。上面使用了新开线程方式来取得错误。

 

 

 

 

 

 

 

 

原创粉丝点击