0

I am coding a Java program with JGit to handle the local Git repository. I am wondering if there is a way to find a committed file via hash in JGit like what the command git file-cat -p does in the terminal? To be specific, given the hash of a file, the program should return the file content if it has been committed before, otherwise, return null. the file to be retrieved can be from any previous commit.

Siyu Zhou
  • 1
  • 2
  • I think this is answered here: https://stackoverflow.com/questions/1685228/how-to-cat-a-file-in-jgit If you already know the object ID (i.e. 'hash') of the file, you can skip to the line `ObjectLoader loader = repository.open(objectId);` – Rüdiger Herrmann May 24 '22 at 16:50
  • Does this answer your question? [How to "cat" a file in JGit?](https://stackoverflow.com/questions/1685228/how-to-cat-a-file-in-jgit) – Rüdiger Herrmann May 26 '22 at 10:57
  • Thank you for your answer. But actually, the post you gave is not what I want. And I found another tutorial which solve my question: https://www.codeaffine.com/2014/10/20/git-internals/ – Siyu Zhou May 30 '22 at 19:54

1 Answers1

0

I found a tutorial that solves my question: https://www.codeaffine.com/2014/10/20/git-internals/

Here is the core code in this tutorial that corresponds to the command git file-cat:

ObjectReader objectReader = repository.newObjectReader();
ObjectLoader objectLoader = objectReader.open( blobId );
int type = objectLoader.getType(); // Constants.OBJ_BLOB
byte[] bytes = objectLoader.getBytes();
String helloWorld = new String( bytes, "utf-8" ) // Hello World!
Siyu Zhou
  • 1
  • 2