如果Runtime.getRuntime()。exec失败,如何抛出错误

时间:2014-11-17 02:03:32

标签: java

我试着跟随:

package ro.gd.ex;

/**
 * Created by roroco on 11/17/14.
 */
public class Ex {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime().exec("echo -n $(date)|xclip --selection clipboard");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

如果我在终端中运行此cmd,则会引发

roroco@roroco ~/Dropbox/jvs/ro-gd $ echo -n $(date)|xclip --selection clipboard
xclip: --selection: No such file or directory
roroco@roroco ~/Dropbox/jvs/ro-gd $ echo $?
1

但是在java中,它什么也没提,我的问题是如何使这个cmd抛出错误。我发现它的退出状态是1。

我的口碑:

roroco@roroco ~/Dropbox/jvs/ro-gd $ lsb_release -a
No LSB modules are available.
Distributor ID: LinuxMint
Description:    Linux Mint 17 Qiana
Release:    17
Codename:   qiana

2 个答案:

答案 0 :(得分:2)

process.waitFor()将返回命令的错误级别,然后只需创建一个新的Exception(可能是IOException)...

public class Ex {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime().exec("echo -n $(date)|xclip --selection clipboard");
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new IOException("Command exited with " + exitCode);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

您也可以考虑使用ProcessBuilder而不是Runtime.getRuntime().exec

public static void main(String[] args) {
    try {
        ProcessBuilder pb = new ProcessBuilder(
                        "echo",
                        "-n",
                        "$(date)|xclip",
                        "--selection",
                        "clipboard"
        );
        pb.redirectError();
        pb.inheritIO();
        Process process = pb.start();
        // Really should be reading the Process's InputStream
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new IOException("Command exited with " + exitCode);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

答案 1 :(得分:1)

如果Runtime.getRuntime()。exec失败,如何抛出错误

process.waitFor();, exitCode为0,为什么? 什么时候: 0 =退出正常。 1 =退出并显示错误。

此Process对象表示的子进程的退出值。按照惯例,值0表示正常终止和1个不良终止..

有些代码是这样的:

进程p = Runtime.getRuntime()。exec(" Seguridad.bat");

        int exitCode = p.waitFor();
        if (exitCode != 0) {
            JOptionPane.showConfirmDialog(null,"Error Execute when exitCode=1");
        }else{
            JOptionPane.showConfirmDialog(null,"fine Execute when exitCode=0");

        }