【发布时间】:2020-09-29 18:41:28
【问题描述】:
我无法读取我在 Java 应用程序中使用 ProcessBuilder 的 git bash 运行的 git 命令的输出。
操作系统:Windows 8.1 --- IDE:IntelliJ
我的代码尝试列出 github 存储库中的所有文件并计算 java 文件类型的数量。
完整的git命令(管道类型):
cd C:/Users/Utente/Documents/Repository-SVN-Git/Bookkeeper && git ls-files | grep .java | wc -l
结果出现在我的 git bash 中,但没有显示在我的 Java 应用程序中,我不明白为什么会这样。
Result in git-bash :
2140
Result in IntelliJ :
--- Command run successfully
--- Output=
这是我的java类:
public class SelectMetrics {
public static final String path_bash = "C:/Program Files/Git/git-bash.exe";
public static final String path_repository = "cd C:/Users/Utente/Documents/Bookkeeper";
public static final String git_command = "git ls-files | grep .java | wc -l";
public static final String command_pipe = path_repository + " && " + git_command;
public static void main(String[] args) {
runCommandPIPE(command_pipe);
}
public static void runCommandPIPE(String command) {
try {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(path_bash, "-c", command);
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println(" --- Command run successfully");
System.out.println(" --- Output=" + output);
} else {
System.out.println(" --- Command run unsuccessfully");
}
} catch (IOException | InterruptedException e) {
System.out.println(" --- Interruption in RunCommand: " + e);
// Restore interrupted state
Thread.currentThread().interrupt();
}
}
}
---- 编辑----
我找到了一种方法来获取 git-bash 输出,方法是将其打印到 txt 文件中,然后从我的 java 应用程序中读取它。在这里你可以找到代码:
Open git bash using processBuilder and execute command in it
但是我还是不明白为什么我不能用 ProcessBuilder 读取输出
【问题讨论】:
标签: java pipe inputstream git-bash processbuilder