How do I run Git commands from Java?


I can run commands, git add , git commit , right from Git. But are there any methods so that I can run commands directly from java.


I don't know how to describe it in Russian. But Java has a Runtime class to work with.

It has a getRuntime() method that returns the appropriate Runtime application, and it also has an exec(String command) method that runs the command represented by the given string in a separate process. The returned object :py:class::java.lang.Process and can be used to control the execution of this process. Actually, they can be used. Example:

Runtime.getRuntime().exec("git add");

Naturally with try/catch and other check constructs


I found a description of the methods in Russian to make it easier to get acquainted. :

class java.lang.Runtime

getRuntime () – Returns the corresponding application's Runtime

exit (int status) public void – Executes the program termination with the status exit code (when using this method, special attention should be paid to exception handling – the exit will be performed instantly, and control in finally will not be transferred in try-catch-finally constructs)

gc () public native void – Signals the garbage collector to run

freeMemory () public native long – Returns the amount of free memory. In some cases, this number can be increased by calling the gc () method on the Runtime object.

totalMemory () public native long – Returns the total amount of memory allocated to the Java machine. This number can change even during one launch, depending on the implementation of the platform on which the Java machine is running. Also, you should not be based on the amount of memory occupied by one specific object – this value also depends on the implementation of the Java machine.

loadLibrary (String libname) public void – Loads the library with the specified name. Typically, loading libraries is done as follows: a static initializer is added in a class that uses native implementations of methods, for example:

static {

Thus, when the class is loaded and initialized, the necessary code to implement native methods will also be loaded. If several calls to load a library with the same name are made, only the first one will be made, and all the others will be ignored.

load (String filename) public void – Loads a file with the specified name as a library. In principle, this method works in the same way as the load () method, only it accepts the name of the file as a parameter, and not the library, thereby allowing you to load any file with native code.

runFinalization () public void – Runs execution of finalize () methods on all objects waiting for it

exec (String command) public Process – Runs the command represented by the given string in a separate process. The returned object: py: class :: java.lang.Process can be used to control the execution of this process.

Scroll to Top