public static void main(String[] args) throws Exception { if (args.length == 0) { usage(); return; } Mode mode = grabMode(args); System.out.println(mode.getMessage() + " " + args[0]); File f = new File(args[0]); if (!f.isFile()) { System.err.println(f + " doesn't exist or is a directory"); } SevenZFile archive = new SevenZFile(f); try { SevenZArchiveEntry ae; while ((ae = archive.getNextEntry()) != null) { mode.takeAction(archive, ae); } } finally { archive.close(); } }
@Override public void takeAction(SevenZFile archive, SevenZArchiveEntry entry) throws IOException { File outFile = new File(entry.getName()); if (entry.isDirectory()) { if (!outFile.isDirectory() && !outFile.mkdirs()) { throw new IOException("Cannot create directory " + outFile); } System.out.println("created directory " + outFile); return; } System.out.println("extracting to " + outFile); File parent = outFile.getParentFile(); if (parent != null && !parent.exists() && !parent.mkdirs()) { throw new IOException("Cannot create " + parent); } FileOutputStream fos = new FileOutputStream(outFile); try { final long total = entry.getSize(); long off = 0; while (off < total) { int toRead = (int) Math.min(total - off, BUF.length); int bytesRead = archive.read(BUF, 0, toRead); if (bytesRead < 1) { throw new IOException( "reached end of entry " + entry.getName() + " after " + off + " bytes, expected " + total); } off += bytesRead; fos.write(BUF, 0, bytesRead); } } finally { fos.close(); } }