gpt4 book ai didi

java - 如果 Runtime.getRuntime().exec 失败如何抛出错误

转载 作者:搜寻专家 更新时间:2023-11-01 03:04:35 25 4
gpt4 key购买 nike

我尝试以下操作:

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

最佳答案

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();
}
}

关于java - 如果 Runtime.getRuntime().exec 失败如何抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26964436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com