java代码调用git命令_使用命令行从Java调用git

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值