logo image

How to clone a Git repository programmatically using Java

JGit (https://eclipse.org/jgit/) is a library developed by Eclipse team and it implements the Git version control system. So let's start with adding the JGit dependency.


If you are using Gradle you can add the following into dependencies section of your build.gradle file

// https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit
compile group: 'org.eclipse.jgit', name: 'org.eclipse.jgit', version: ''

If you are using maven add the following dependency to your pon.xml

<!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->

Using JGit to checkout code

Now using the following code you can checkout a repository

String repoUrl = "https://github.com/onecompiler/tutorials.git";
String cloneDirectoryPath = "/path/to/directory/"; // Ex.in windows c:\\gitProjects\SpringBootMongoDbCRUD\
try {
    System.out.println("Cloning "+repoUrl+" into "+repoUrl);
    System.out.println("Completed Cloning");
} catch (GitAPIException e) {
    System.out.println("Exception occurred while cloning repo");