【问题标题】:Open git bash and run command in java on Windows在 Windows 上打开 git bash 并在 java 中运行命令
【发布时间】:2020-01-03 00:45:36
【问题描述】:

我在 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();

【问题讨论】:

    标签: java bash curl


    【解决方案1】:

    是否需要弹出 bash 终端? 如果没有,这可以工作

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class testprog {
        public static void main(String args[]) {
            String s;
            Process p;
            try {
                p = Runtime.getRuntime().exec("ls -aF");
                BufferedReader br = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
                while ((s = br.readLine()) != null)
                    System.out.println("line: " + s);
                p.waitFor();
                System.out.println ("exit: " + p.exitValue());
                p.destroy();
            } catch (Exception e) {}
        }
    }
    

    【讨论】:

    • 我不需要终端弹出。我运行了它,它给了我“CreateProcess error=2,系统找不到指定的文件”。另外,由于我使用的是 windows,这不会在 windows cmd 上运行吗?
    【解决方案2】:

    您只需要更改路径和 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

    【讨论】:

      【解决方案3】:

      如果您安装了 Git,而无需将输出写入临时文件,这将在 Windows 上执行 bash 脚本。

      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import java.util.StringJoiner;
      
      public class BashRunner
      {
          public static final String BASH_PATH = "C:/Program Files/Git/bin/sh.exe";
          public static final String SCRIPT_NAME = "C:/temp/test-script.sh";
      
          public static void main(String[] args)
          {
              String output = runCommand(BASH_PATH, "-c", SCRIPT_NAME);
              System.out.println(output);
          }
      
          public static String runCommand(String... params)
          {
              ProcessBuilder pb = new ProcessBuilder(params);
              Process p;
              StringJoiner joiner = new StringJoiner(System.getProperty("line.separator"));
              try
              {
                  p = pb.start();
      
                  final BufferedReader reader = new BufferedReader(
                      new InputStreamReader(p.getInputStream()));
      
                  reader.lines().iterator().forEachRemaining(joiner::add);
      
                  p.waitFor();
                  p.destroy();
              }
              catch (Exception e)
              {
                  e.printStackTrace();
              }
      
              return joiner.toString();
          }
      }
      

      脚本内容:

      #!/bin/bash
      
      echo "hello"
      echo "world!"
      

      输出:

      hello
      world!
      

      此外,这将静默执行 Git Bash,因为您在处理时不会弹出窗口。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-10
        • 2021-06-06
        • 2022-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多