jGit - pure Java library implementing Git

Today we have a quick glimpse at JGit.

JGit is an EDL (new-style BSD) licensed, lightweight, pure Java library implementing the Git version control system:

  • repository access routines
  • network protocols
  • core version control algorithms

Let's create a local directory to work with:

File workingDir = File.createTempFile("GitWorkingDirectory", "");

and clone (without checkout - we want to grab single files later)

try (Git git = Git.cloneRepository()
    .call()) {

  ... work with the Git repository

As mentioned above we want the content of a single file as OutputStream:

private static void streamRemoteFile(OutputStream outStream, Git git) {
  try (TreeWalk walk = new TreeWalk(git.getRepository());
  RevWalk rw = new RevWalk(walk.getObjectReader())) {


    while (walk.next()) {
      String name = walk.getPathString();
      FileMode mode = walk.getFileMode(0);

      if (walk.isSubtree())

      if (mode == FileMode.TREE) {
        continue;  // skip directories

      MutableObjectId idBuf = new MutableObjectId();
      ObjectReader reader = walk.getObjectReader();

      walk.getObjectId(idBuf, 0);
  } catch (IOException e) {
      throw new RuntimeException("Failed to open remote stream...");

With the ArchiveCommand available via Git.archive we can get the content as archive:

try (Git git = new Git( repository )) {
    .setPaths( "README.md" )
    .setTree( git.getRepository()
    .resolve( "origin/" + context.getJobConfiguration().getGitConfiguration().getBranch() ) )
    .setOutputStream( createTempFile("archive", ".zip") )
    .setFormat( "zip" )

For more examples see centic9/jgit-cookbook.

Show Comments