2

I need to add the file to the repository and then commit it from my java project. I use

Runtime.getRuntime().exec("C:\\Program Files (x86)\\Git\\bin\\sh.exe");

to start git but what should I do next?

3 Answers 3

4

Instead of running the command line tool directly from your Java application, consider using Git APIs for Java, such as JavaGit. The cookbook has examples that you can follow.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. Now I try to solve the problem with "020100: Unable to start sub-process." Could you give me advice why could this occur?
I had to add git path to system environment. I got it. Problem has solved. Thx
3

I code should be something like this:

public void gitCommands() throws IOException {

   // Build command 
   List<String> commands = new ArrayList<String>();
   commands.add("/bin/bash");
   commands.add("-c");
   commands.add("git add .");       

   StringBuilder out = new StringBuilder();

   ProcessBuilder pb = new ProcessBuilder(commands);
   pb.redirectErrorStream(true);
   process process = pb.start();


   //EDIT:
   // get Exit Status   
   process.waitFor();


   //go for next commands
   .....

}

3 Comments

Better to wait for the process to finish instead of sleeping for an arbitrary duration. Also, beware of typos in this example. It won't work out of the box.
thanks, I guess it is better use process.waitFor(), isn't it ?
Yes. There are very few legitimate uses of sleep().
2

sh.exe isn't Git, it's the command shell distributed with Git. You'd want to run Git directly, e.g. like this:

String[] command = {"C:\\Program Files (x86)\\Git\\bin\\git.exe",
                    "add",
                    "some-file-to-add"};
Runtime.getRuntime().exec(command);

But since you're writing in Java I suggest you have a look at JGit, a native Java Git library.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.