Sunday, December 18, 2011

Extracting RAR Archives in Java using JUnrar

I just found a wonderful open source RAR Archives library in Java, jUnrar. It seems this project moved from and document is still on the way. There is a JUnit test project comes with the source shows how to use it. I modified it a little bit to make is simpler.

The following code will extract mytest.rar into the user home directory.

1. construct rar Archive from File
File rarFile = new File("mytest.rar");
Archive archive = new Archive(rarFile);

The extraction is working around FileHeader, which represent each entry in the rar archive. It could be file or directory.

There are two things we need to pay attention:

2. It is safe to ignore directory if you don't care about empty directory, since FileHeader will give you full path of file and Java will create directory for your file if it doesn't exist.

3. Determine file name
If the file name is unicode, you need to use getFileNameW(). But if it is not, this method will give you empty String. So we have to check

FileHeader fileHeader = archive.nextFileHeader();
  while (fileHeader != null) {


   //2. extract file only, ignore directory since it will be created
   // along with file
   if (!fileHeader.isDirectory()) {

// 3.determine file name
   String name;

   if (fileHeader.isUnicode()) {
    name = fileHeader.getFileNameW();

   } else {
    name = fileHeader.getFileNameString();

   System.out.println("find header:" + name);
    String userHome = System.getProperty("user.home");
    String separator = System.getProperty("file.separator");
    String targetPath = userHome + separator + name;

    OutputStream stream = new FileOutputStream(new File(targetPath));
    archive.extractFile(fileHeader, stream);


   // go to next file
   fileHeader = archive.nextFileHeader();