8

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?

David Georg Reichelt
  • 963
  • 1
  • 15
  • 36

2 Answers2

2

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.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

If you absolutely need to run command line git you may consider using JavaGit (it may be a bit outdated). But the currently recommended way to manage Git repositories from within Java is to use JGit - a pure Java implementation of Git storage. Eclipse EGit plugin is built on top of JGit

user3159253
  • 16,836
  • 3
  • 30
  • 56