linux 命令的输出未在 java 中捕获
The output of linux command is not captured in java
我正在尝试 运行 来自 java 的以下命令并希望捕获输出。该方法立即完成,无需向控制台写入任何内容。
Linux 命令是 repo forall -c 'echo pwd is;pwd;git status'
方法是
public static String executeCommandWithOutput(String command) {
System.out.println("Running the command "+command);
StringBuffer output = new StringBuffer();
String line = "";
try {
Process process =Runtime.getRuntime().exec(command);
process.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = reader.readLine())!= null) {
output.append(line);
}
System.out.println("Content is "+output.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return output.toString();
}
我也尝试将输出重定向到一个文件。都没有用。有什么想法吗??
检查您尝试执行的命令是否有标准输出。
可能它失败了,你得到了错误输出。
您可以使用 getErrorStream
检查错误输出,文档是 here。
例如像这样
StringBuffer error = new StringBuffer();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = reader.readLine())!= null) {
error.append(line);
}
System.out.println("Error is " + error.toString());
还要检查你的分叉命令的 exitValue
,doc 是 here
int exitStatus = process.exitValue();
System.out.println("Exit status is " + exitStatus );
我正在尝试 运行 来自 java 的以下命令并希望捕获输出。该方法立即完成,无需向控制台写入任何内容。
Linux 命令是 repo forall -c 'echo pwd is;pwd;git status'
方法是
public static String executeCommandWithOutput(String command) {
System.out.println("Running the command "+command);
StringBuffer output = new StringBuffer();
String line = "";
try {
Process process =Runtime.getRuntime().exec(command);
process.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = reader.readLine())!= null) {
output.append(line);
}
System.out.println("Content is "+output.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return output.toString();
}
我也尝试将输出重定向到一个文件。都没有用。有什么想法吗??
检查您尝试执行的命令是否有标准输出。
可能它失败了,你得到了错误输出。
您可以使用 getErrorStream
检查错误输出,文档是 here。
例如像这样
StringBuffer error = new StringBuffer();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = reader.readLine())!= null) {
error.append(line);
}
System.out.println("Error is " + error.toString());
还要检查你的分叉命令的 exitValue
,doc 是 here
int exitStatus = process.exitValue();
System.out.println("Exit status is " + exitStatus );