java - 在 Windows 上打开 git bash 并在 java 中运行命令
问题描述
我在 Windows 上使用 java,并且想调用 Linux 命令,所以我试图打开 git bash 并粘贴一些命令。我可以打开 git bash 但无法粘贴任何内容。
这会很好地打开 git bash:
String [] args = new String[] {"C:\\Progam Files\\Git\\git-bash.exe"}
Process proc = new ProcessBuilder(args).start();
当我这样做时, git bash 打开但立即关闭:
String [] args = new String[] {"C:\\Progam Files\\Git\\git-bash.exe", "-c", "cd c:"}
Process proc = new ProcessBuilder(args).start();
解决方案
您只需要更改路径和 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
推荐阅读
- automation - 从 MQTT 主题或有效负载中读取信息以作为字符串插入?
- php - Pandoc在编织.Rmd文件时导致问题(Raspbian)
- javascript - 有没有更简洁的方法来编写没有一堆 IF 语句?
- javascript - 如何解决 AngularJs - 路由不起作用
- sql - 如何获得访问中的最大值?
- c# - 使用 bouncycastle 在 C# 中使用 cryptodome 解密在 python 中加密的 RSA 数据会导致错误块不正确
- python - 使用 Python 脚本打开选项卡
- javascript - 传单多边形突出显示问题
- excel - 溢出范围:将数组转换为与 @ 的交集值
- angularjs - Angularjs 1.7.9 - 可能未处理的拒绝