java - 使用 processBuilder 打开 git bash 并在其中执行命令
问题描述
是否可以在 java 中使用 ProcessBuilder 之类的东西打开 gitbash,编写命令(例如 git status)并输出结果?
我可以使用以下代码成功打开 git bash,但我不知道如何在其中编写任何命令。
String[] commands = {"cmd","/C","C:\\Users\\......\\Git\git-bash"};
ProcessBuilder builder = new ProcessBuilder(commands);
builder.redirectErrorStream(true);
Process process = builder.start();
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try
{
br=new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + System.getProperty("line.seperator"));
}
} finally {
br.close();
}
String outcome = get_output(process.getInputStream());
process.waitFor();
System.out.println("Process finished with outcome = " + outcome);
解决方案
您只需要更改路径和 git 命令。但是 git-bash 输出打印在单独的 .txt 文件中,因为我无法以任何其他方式读取它。
public class GitBash {
public static final String path_bash = "C:/Program Files/Git/git-bash.exe";
// Create a file Output.txt where git-bash prints the results
public static final String path_file_output_git_bash =
"C:/Users/Utente/Documents/IntelliJ-DOC/IntelliJ_project/Prova/src/main/Git-bash/Output.txt";
public static void main(String[] args) {
// Path to your repository
String path_repository = "cd C:/Users/Utente/Documents/Repository-SVN-Git/Bookkeeper";
// Git command you want to run
String git_command = "git ls-files | grep .java | wc -l";
String command = path_repository + " && " + git_command + " > " + path_file_output_git_bash;
runCommand(command);
}
public static void runCommand(String command) {
try {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(path_bash, "-c", command);
Process process = processBuilder.start();
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println(" --- Command run successfully");
System.out.println(" --- Output = " + readFileTxt());
} else {
System.out.println(" --- Command run unsuccessfully");
}
} catch (IOException | InterruptedException e) {
System.out.println(" --- Interruption in RunCommand: " + e);
// Restore interrupted state
Thread.currentThread().interrupt();
}
}
public static String readFileTxt() {
String data = null;
try {
File myObj = new File(path_file_output_git_bash);
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println(" --- An error occurred");
e.printStackTrace();
}
return data;
}
}
}
--- 编辑 2021/03/26 ---
无需 .txt 文件即可回答:Read output git-bash with ProcessBuilder in Java
推荐阅读
- reactjs - rxjs 可观察捕获错误上缺少“body”属性
- lua - “内存分配错误:块太大”做简单的整数除法
- ngx-admin - ngx-admin 卡片填充和边距
- terraform - 我们如何从 terraform gcp 资源 iam 绑定中的变量添加项目编号
- python - 通过阈值使用通用句子编码器的句子相似度
- ruby-on-rails - 即使禁用缓存,Rails 仍会缓存视图/控制器
- c# - C# 解析 JSON 对象
- verilog - 使用 yosys-smtbmc 证明时是否可以使用 $display 打印一些值?
- node.js - 也找不到名称空间“NodeJS”与类型节点
- list - 访问列表从一个飞镖飘到另一个飞镖