java - 在 Java 中使用 ProcessBuilder 读取输出 git-bash
问题描述
我无法读取我在 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 应用程序中读取它。在这里你可以找到代码:
使用 processBuilder 打开 git bash 并在其中执行命令
但是我仍然不明白为什么我无法使用 ProcessBuilder 读取输出
解决方案
问题应该是在使用
C:/Program Files/Git/git-bash.exe
因为它打开了用户用于工作的窗口,但在运行时在 java 应用程序中你应该使用
C:/Program Files/Git/bin/bash.exe
通过这种方式ProcessBuilder可以读取 git 操作的结果。
ProcessBuilder无法从窗口git-bash.exe读取,读取结果为空是正确的。如果在运行时在 git-bash.exe 中运行命令,结果将仅显示在git-bash.exe窗口中,Java 应用程序无法读取它。
--- 编辑 2021/03/26 ---
总之,要使用 git-bash 运行命令并在您的 java 应用程序运行时从中读取输出,您必须更改我的问题代码:
public static final String path_bash = "C:/Program Files/Git/bin/bash.exe";
然后
Result in git-bash :
2183
Result in IntelliJ :
--- Command run successfully
--- Output=2183
推荐阅读
- sockets - 错误“已建立的连接被主机中的软件中止”
- r - 因子错误(newCases[, a], levels = 1:nlevels(data[, a]), labels = levels(data[, : invalid 'labels'; 长度 0 应该是 1 或 2
- java - NoNodeAvailableException[配置的节点都不可用] Elasticsearch
- simulation - 如何将我的 OMNeT++ 模型导出为 FMU(功能模型单元)?
- elasticsearch - Elasticsearch - 按大于特定值的多个字段的总和过滤
- object - 在组件之间共享对象
- docker - Dockerfile 在一行中定义多个 ARG 参数
- javascript - 选择或提取单个基于 JavaScript 动画的代码的最有效方法是什么?
- java - 如何加入 Solr 集合?
- r - 识别数组中的最大分数