我正在尝试运行一些 bash 命令,这些命令在我的控制台上运行良好,但在尝试从 Java 内部进行相同的命令调用时失败。该命令不返回任何错误,并且无法生成所需的输出文件。该命令假设使用 PGP 工具 (GPG) 解密一个文件并创建另一个文件。这在手动运行时有效,但不能在 Java 应用程序中进行相同的 shell 调用且没有错误。
为了确保我什至在容器文件夹上尝试了 chmod 777,所以我认为这不是权限问题。
Shell 执行器代码(由 Mkyong.com 提供)
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
实际 Shell 命令
gpg --output /main/decrypted-token.txt --passphrase test /main/token.asc
最佳答案
如果该命令在终端上运行良好,但在从 Java 脚本调用时运行不正常,我会尝试的第一件事是在被调用的命令上指定 Bash,看看这是否有效:
bash -c "gpg --output /main/decrypted-token.txt --passphrase test /main/token.asc"
或者更好:
/bin/bash -c "gpg --output /main/decrypted-token.txt --passphrase test /main/token.asc"
关于java - Shell 命令从 java 失败,但在手动运行时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41127734/