package net.sourceforge.javautil.common;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import net.sourceforge.javautil.common.exception.ThrowableManagerRegistry;
import net.sourceforge.javautil.common.io.IVirtualFile;
/**
* Utility methods related to archives, like {@link ZipFile}'s.
*
* @author elponderador
* @author $Author: ponderator $
* @version $Id: ArchiveUtil.java 2297 2010-06-16 00:13:14Z ponderator $
*/
public class ArchiveUtil {
public static final String[] ARCHIVE_EXTENSIONS = { "zip", "jar", "rar", "war", "ear" };
/**
* @param extension The extension to compare
* @return True if the extension matches one of the standard archive extensions, otherwise false
*/
public static boolean isArchive (String extension) {
for (String ext : ARCHIVE_EXTENSIONS) if (ext.equalsIgnoreCase(extension)) return true;
return false;
}
/**
* @param file The file to compare
* @return True if the ending part of the file name matches a period '.' and one of the standard archive extensions, otherwise false
*/
public static boolean isArchive (File file) {
for (String ext : ARCHIVE_EXTENSIONS) if (file.getName().endsWith("." + ext)) return true;
return false;
}
/**
* This passes the {@link IVirtualFile#getExtension()} to {@link #isArchive(String)}.
*/
public static boolean isArchive (IVirtualFile file) { return isArchive (file.getExtension()); }
/**
* NOTE: The input stream will be closed after this operation.
*
* @param input The original input stream
* @param entryName The name of the entry to get the data for
* @return The binary data for the entry, or null if it does not exist or could not be found
*/
public static byte[] getZipEntryData (InputStream input, String entryName) throws IOException {
try {
ZipInputStream zis = new ZipInputStream(input);
ZipEntry entry = null;
byte[] buffer = new byte[10956];
while ( (entry = zis.getNextEntry()) != null ) {
if (entry.getName().equals(entryName)) {
return IOUtil.read(zis, buffer, false);
}
}
return null;
} finally {
try { input.close(); } catch (IOException e) { ThrowableManagerRegistry.caught(e); }
}
}
}