How to “cat” a file in JGit?

后端 未结 7 617
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 04:25

A while back I was looking for an embeddable distributed version control system in Java, and I think I have found it in JGit, which is a pure Java implementation of git. How

7条回答
  •  眼角桃花
    2020-12-01 04:54

    Figured it out by myself. The API is quite low-level, but it's not too bad:

    File repoDir = new File("test-git/.git");
    // open the repository
    Repository repo = new Repository(repoDir);
    // find the HEAD
    Commit head = repo.mapCommit(Constants.HEAD);
    // retrieve the tree in HEAD
    Tree tree = head.getTree();
    // find a file (as a TreeEntry, which contains the blob object id)
    TreeEntry entry = tree.findBlobMember("b/test.txt");
    // use the blob id to read the file's data
    byte[] data = repo.openBlob(entry.getId()).getBytes();
    

提交回复
热议问题