Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created May 17, 2024 16:16
Show Gist options
  • Save aspose-com-gists/ff3076d888bde5d08e65a99a8b092297 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/ff3076d888bde5d08e65a99a8b092297 to your computer and use it in GitHub Desktop.
Convert RAR to ZIP in Java
package com.example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import com.aspose.zip.Archive;
import com.aspose.zip.RarArchive;
import com.aspose.zip.RarArchiveEntry;
import com.aspose.zip.exceptions.IOException;
public class Main {
// Convert RAR to ZIP in Java
public static void main(String[] args) throws java.io.IOException {
// Define the directory path.
String dir = "/Desktop/";
// Create an instance of the Archive class.
try (Archive zip = new Archive()) {
// Initialize an object of the RarArchive class with the source RAR file.
try (RarArchive rar = new RarArchive(dir+"sample.rar")) {
// Loop through the entries returned by the getEntries method.
for (int i = 0; i < rar.getEntries().size(); i++) {
RarArchiveEntry entry = rar.getEntries().get(i);
if (!entry.isDirectory()) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
entry.extract(out);
try (ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray())) {
zip.createEntry(entry.getName(), in);
}
}
} else {
zip.createEntry(entry.getName() + "/", new ByteArrayInputStream(new byte[0]));
}
}
}
// Invoke the save method to save the output ZIP file on the disk.
zip.save(dir+"output.zip");
} catch (IOException ex) {
System.out.println(ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment