[英]Problems in running AWS CLI bash command within Java
I'm trying to run an AWS command within Java code (in Linux).我正在尝试在 Java 代码中运行 AWS 命令(在 Linux 中)。 Like always, I try to run the bash command like this in Java.
像往常一样,我尝试在 Java 中像这样运行 bash 命令。 But I wonder it doesn't show anything.
但我想知道它没有显示任何内容。 And just prints
Exited with error code : 2
.并且只打印
Exited with error code : 2
。 When I just run aws ls help
in bash, it works.当我在 bash 中运行
aws ls help
时,它可以工作。
What is the problem?问题是什么? How to solve it?
如何解决?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestCMD {
public static void main(String[] args) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", "aws ls help");
try {
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The Java code is not the problem. Java 代码不是问题。 It works fine, what you can check by replacing the
command
with它工作正常,您可以通过将
command
替换为
processBuilder.command("bash", "-c", "echo 1 2 3");
You have 2 "problems".你有两个“问题”。 The first problem is that
aws
writes its output to stderr, not stdout.第一个问题是
aws
将其输出写入 stderr,而不是 stdout。
The second problem is that aws
returns 2 where 0
would be IMHO better.第二个问题是
aws
返回 2 ,其中0
恕我直言更好。
You can test this on the commandline with:您可以在命令行上使用以下命令进行测试:
aws ls help 2>/dev/null; echo $?
The problems can be fixed with问题可以解决
processBuilder.command("bash", "-c", "/usr/bin/aws ls help 2>&1; true");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.