Java運行系統命令

來源:互聯網
上載者:User

之前寫過一個版本的Java代碼用來調用linux shell指令碼,原文如下:

http://blog.csdn.net/sheismylife/article/details/4817851

不過沒有試過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;    }}

最重要的Command.java代碼:

package command;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * Describe class Command here. * */public class Command {    private long startTime;    private long timeout;    private static final long INTERVAL = 500;    /*     * command is one system command represented by string     * timeout is milliseconds for waiting the command execution     * throw CommandError if the system command can't be executed     * return CommandResult when the system command is executed no matter what the command returns(succeed or failed)     */    public CommandResult exec(final String command, long timeout) throws CommandError {        this.timeout = timeout;        try {            Process process = Runtime.getRuntime().exec(command);            CommandResult result = wait(process);            if (process != null) {                process.destroy();            }            return result;        } catch (Exception ex) {            throw new CommandError(ex);        }    }    private boolean isTimeout() {        return System.currentTimeMillis() - startTime >= timeout;    }    private CommandResult wait(final Process process) throws InterruptedException, IOException {        BufferedReader errorStreamReader = null;        BufferedReader inputStreamReader = null;        try {            errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));            inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));            //timeout control            startTime = System.currentTimeMillis();            boolean isFinished = false;            for (;;) {                if (isTimeout()) {                    CommandResult result = new CommandResult();                    result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);                    result.setOutput("Command process timeout");                    return result;                }                if (isFinished) {                    CommandResult result = new CommandResult();                    result.setExitValue(process.waitFor());                    //parse error info                    if (errorStreamReader.ready()) {                        StringBuilder buffer = new StringBuilder();                        String line;                        while ((line = errorStreamReader.readLine()) != null) {                            buffer.append(line);                        }                        result.setError(buffer.toString());                    }                    if (inputStreamReader.ready()) {                        StringBuilder buffer = new StringBuilder();                        String line;                        while ((line = inputStreamReader.readLine()) != null) {                            buffer.append(line);                        }                        result.setOutput(buffer.toString());                    }                    return result;                }                try {                    isFinished = true;                    process.exitValue();                } catch (IllegalThreadStateException e) {                    // process hasn't finished yet                    isFinished = false;                    Thread.sleep(INTERVAL);                }            }        } finally {            if (errorStreamReader != null) {                try {                    errorStreamReader.close();                } catch (IOException e) {                }            }            if (inputStreamReader != null) {                try {                    inputStreamReader.close();                } catch (IOException e) {                }            }        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.