java decompress rar archive

After recording the relevant coordinates of importing maven, the rar package was not found under the archivers package

import org.apache.commons.compress.archivers.rar.RarArchiveEntry;

Java itself does not provide the function of decompressing RAR archives, which needs to be implemented with the help of a third-party library. The following is a sample code to decompress a RAR archive using the Apache Commons Compress library:

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.rar.RarArchiveEntry;
import org.apache.commons.compress.archivers.rar.RarArchiveInputStream;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class RarExtractor {
    public static void extract(String rarFile, String destDir) throws IOException, ArchiveException {
        File destinationDir = new File(destDir);
        if (!destinationDir.exists()) {
            destinationDir.mkdirs();
        }
        try (ArchiveInputStream in = new ArchiveStreamFactory()
                .createArchiveInputStream(ArchiveStreamFactory.RAR, new FileInputStream(rarFile))) {
            RarArchiveInputStream rarIn = (RarArchiveInputStream) in;
            RarArchiveEntry entry;
            while ((entry = (RarArchiveEntry) rarIn.getNextEntry()) != null) {
                if (entry.isDirectory()) {
                    new File(destinationDir, entry.getName()).mkdirs();
                } else {
                    File outputFile = new File(destinationDir, entry.getName());
                    FileOutputStream out = new FileOutputStream(outputFile);
                    IOUtils.copy(rarIn, out);
                    out.close();
                }
            }
        }
    }
    public static void main(String[] args) throws IOException, ArchiveException {
        String rarFile = "path/to/your/rar/file.rar";
        String destDir = "path/to/your/destination/directory";
        extract(rarFile, destDir);
    }
}

This sample code extracts the files in the archive by parsing the header of the RAR file. During the decompression process, they write the extracted content to new files in the target directory. To use this sample code, you need to first add the Apache Commons Compress library to your Java project's classpath.

Guess you like

Origin blog.csdn.net/qq_34412985/article/details/131449127