使用命令行从Java调用git [英] Calling git from Java with command line

查看:1102
本文介绍了使用命令行从Java调用git的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图调用一个git命令时,它在正常的命令行中从Java中正确执行,我得到一个奇怪的结果:它不输出任何内容。



例如,如果我尝试运行此操作:

  public class GitTest {
public static void main(String args [])throws IOException {
String command =git clone http://git-wip-us.apache.org/repos/asf/accumulo。混帐;
进程p = Runtime.getRuntime()。exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
字符串行;
String text = command +\\\
;
System.out.println(text); ((line = input.readLine())!= null){
text + = line;
while
System.out.println(Line:+ line);



code
$ b我没有输出(除了对于之前打印的命令)。看起来git仍在下载内容,但没有告诉我。也许它会在它完成后输出所有东西(所以正常的git调用输出,准备好了多少,并且每次都改变这一行 - 也许正因为如此,BufferedReader无法读取完成的行,因此不会输出它)。



是否有任何解决方法,以使其工作?

解决方案

您需要检查如果git clone的某些(或大部分)输出在stdout或stderr上(就是这种情况,例如git push )。

如果是后者,请参阅 一个href =https://stackoverflow.com/a/236873/6309>这个例子来读取stdout和stderr。



然后使用数组作为你的命令的参数(正如我在 Runtime.getRuntime()。exec() code> )。

另见从Java调用进程


When trying to call a git command, that is executed properly in normal command line, from Java, I get an strange result: it outputs nothing.

For example, if I try to run this:

public class GitTest {
    public static void main(String args[]) throws IOException{
        String command = "git clone http://git-wip-us.apache.org/repos/asf/accumulo.git";
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line; 
        String text = command + "\n";
        System.out.println(text);
        while ((line = input.readLine()) != null) {
            text += line;
            System.out.println("Line: " + line);
        }
    }
}

I get no output (except for the command, which is printed before). It seems like git is still downloading something, but does not tell it to me. Maybe it would output everything after it's completed (so the normal git call outputs, how much is ready, and changes this line everytime - maybe because of this the BufferedReader can not read a finished line and therefore not output it).

Is there any workaround, to get this working?

解决方案

You need to check if some (or most of) the output of git clone is on stdout or stderr (it is the case, for instance, for git push).

If it is the latter, see this example to read both stdout and stderr.

And use an array for the parameters of your command (as I did in "Runtime.getRuntime().exec()").
See also Invoking Processes from Java.

这篇关于使用命令行从Java调用git的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆