Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling git from Java with command line

Tags:

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?

like image 329
David Georg Reichelt Avatar asked Apr 30 '14 08:04

David Georg Reichelt


1 Answers

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.

like image 190
VonC Avatar answered Sep 22 '22 06:09

VonC