下面列出了java.util.zip.ZipEntry#isDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static File unZip(final File zippedFile) throws IOException {
File outputFolder = Files.createTempDir();
try (ZipFile zipFile = new ZipFile(zippedFile)) {
final Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
final File entryDestination = new File(outputFolder, entry.getName());
if (entry.isDirectory()) {
//noinspection ResultOfMethodCallIgnored
entryDestination.mkdirs();
} else {
//noinspection ResultOfMethodCallIgnored
entryDestination.getParentFile().mkdirs();
final InputStream in = zipFile.getInputStream(entry);
final OutputStream out = new FileOutputStream(entryDestination);
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
out.close();
}
}
}
return outputFolder;
}
public void write(ZipFile zip, ZipEntry entry) throws IOException {
track("A", entry.getName());
boolean changeCompressionLevel = !compressedLevel && CompressionUtil.ENV_SUPPORTS_COMPRESSION_LEVEL_CHANGE;
if (changeCompressionLevel) {
// The entry to be written is assumed to be incompressible
jOut.setLevel(NO_COMPRESSION);
}
exportInfo.update(ExportInfo.Type.ADD, entry.getName());
ZipEntry copy = new ZipEntry(entry);
copy.setCompressedSize(-1);
jOut.putNextEntry(copy);
if (!entry.isDirectory()) {
// copy
try (InputStream in = zip.getInputStream(entry)) {
IOUtils.copy(in, jOut);
}
}
jOut.closeEntry();
if (changeCompressionLevel) {
jOut.setLevel(level);
}
}
/**
* Unzips an internal resource to a targeted path.Does not check header.
*
* @param internalPath Path to internal zipped resource
* @param target destination to unzip to
* @throws java.io.IOException
*/
public static void unzipResourceToDir(String internalPath, Path target) throws IOException {
InputStream fin = IOHandler.class.getResourceAsStream(internalPath);
try (ZipInputStream zin = new ZipInputStream(fin)) {
ZipEntry ze;
while ((ze = zin.getNextEntry()) != null) {
File extractTo = new File(target + File.separator + ze.getName());
if (ze.isDirectory()) {
extractTo.mkdir();
} else {
try (FileOutputStream out = new FileOutputStream(extractTo)) {
int nRead;
byte[] data = new byte[16384];
while ((nRead = zin.read(data, 0, data.length)) != -1) {
out.write(data, 0, nRead);
}
}
}
}
}
}
/**
* Retrieves the named object.
*
* @param strName the name of the object to look up
* @return the object bound to name
*/
@Override
protected Object doLookup(String strName) {
Name name;
try {
name = getEscapedJndiName(strName);
} catch (InvalidNameException e) {
log.info(sm.getString("resources.invalidName", strName), e);
return null;
}
if (name.isEmpty())
return this;
Entry entry = treeLookup(name);
if (entry == null)
return null;
ZipEntry zipEntry = entry.getEntry();
if (zipEntry.isDirectory())
return new WARDirContext(base, entry);
else
return new WARResource(entry.getEntry());
}
/**
* adds a .jar file to the repository
*
* @param filename name of .jar file
*/
public static void addJarFile(String filename) {
try {
if (knownFiles.contains(filename)) {
return;
}
File file = new File(filename);
if (!file.canRead()) {
return;
}
knownFiles.add(filename);
ZipFile zipFile = new ZipFile(file);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
String name = stripLeadingSlash(entry.getName());
contentFilenameMapping.put(name, file);
contentZipFilesMapping.put(name, zipFile);
}
}
} catch (IOException e) {
logger.error(e, e);
}
}
public static void extractZipFile(String filePath, String targetDir)
{
try
{
ZipFile zipFile = new ZipFile(filePath);
Enumeration entries = zipFile.entries();
File unzipDir = new File(targetDir);
if (!unzipDir.exists())
{
unzipDir.mkdir();
}
while (entries.hasMoreElements())
{
ZipEntry entry = (ZipEntry) entries.nextElement();
String name = entry.getName();
if (!entry.isDirectory() && !name.startsWith("/") && !name.startsWith("_"))
{
String file = targetDir+"/"+name;
copyInputStream(zipFile.getInputStream(entry),
new BufferedOutputStream(new FileOutputStream(file)));
}
}
zipFile.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private void unzip() { //Oh, naughty~
String folder = Environment.getExternalStorageDirectory().getAbsolutePath() + AppConstants.themeFolder;
String zipFile = folder + "builtin.zip";
try {
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
if(ze.isDirectory()) {
File f = new File(folder + ze.getName());
if(!f.isDirectory()) {
f.mkdirs();
}
} else {
FileOutputStream fout = new FileOutputStream(folder + ze.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
bufout.close();
zin.closeEntry();
fout.close();
}
}
zin.close();
new File(zipFile).delete();
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public InputStream open(String path) throws IOException {
ZipEntry entry = archive.getEntry(path);
if (entry == null) {
throw new FileNotFoundException("File \"" + path + "\" not found");
} else if (entry.isDirectory()) {
throw new DirectoryEntryException();
} else {
return archive.getInputStream(entry);
}
}
public static void upZipFile(Context context,String assetPath,String outputFolderPath){
File desDir = new File(outputFolderPath);
if (!desDir.isDirectory()) {
desDir.mkdirs();
}
try {
InputStream inputStream = context.getResources().getAssets().open(assetPath);
ZipInputStream zipInputStream=new ZipInputStream(inputStream);
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
Log.d(TAG, "upZipFile: "+zipEntry.getName());
if(zipEntry.isDirectory()) {
File tmpFile=new File(outputFolderPath,zipEntry.getName());
//Log.d(TAG, "upZipFile: folder "+tmpFile.getAbsolutePath());
if(!tmpFile.isDirectory())
tmpFile.mkdirs();
} else {
File desFile = new File(outputFolderPath +"/"+ zipEntry.getName());
if(desFile.exists()) continue;
OutputStream out = new FileOutputStream(desFile);
//Log.d(TAG, "upZipFile: "+desFile.getAbsolutePath());
byte buffer[] = new byte[1024];
int realLength;
while ((realLength = zipInputStream.read(buffer)) > 0) {
out.write(buffer, 0, realLength);
}
zipInputStream.closeEntry();
out.close();
}
}
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean expandZippedApplication(InputStream stream, ApplicationDescription desc)
throws IOException {
boolean isSelfContained = false;
ZipInputStream zis = new ZipInputStream(stream);
ZipEntry entry;
File appDir = new File(appsDir, desc.name());
if (!FilePathValidator.validateFile(appDir, appsDir)) {
throw new ApplicationException("Application attempting to create files outside the apps directory");
}
while ((entry = zis.getNextEntry()) != null) {
if (!entry.isDirectory()) {
byte[] data = ByteStreams.toByteArray(zis);
zis.closeEntry();
if (FilePathValidator.validateZipEntry(entry, appDir)) {
File file = new File(appDir, entry.getName());
if (isTopLevel(file)) {
createParentDirs(file);
write(data, file);
} else {
isSelfContained = true;
}
} else {
throw new ApplicationException("Application Zip archive is attempting to leave application root");
}
}
}
zis.close();
return isSelfContained;
}
private static void unzipPythonLibrary(Path targetDir) throws IOException {
FileSystem targetFs = targetDir.getFileSystem();
ClassLoader classLoader = PythonPlanBinder.class.getClassLoader();
try (ZipInputStream zis = new ZipInputStream(classLoader.getResourceAsStream("python-source.zip"))) {
ZipEntry entry = zis.getNextEntry();
while (entry != null) {
String fileName = entry.getName();
Path newFile = new Path(targetDir, fileName);
if (entry.isDirectory()) {
targetFs.mkdirs(newFile);
} else {
try {
LOG.debug("Unzipping to {}.", newFile);
FSDataOutputStream fsDataOutputStream = targetFs.create(newFile, FileSystem.WriteMode.NO_OVERWRITE);
IOUtils.copyBytes(zis, fsDataOutputStream, false);
} catch (Exception e) {
zis.closeEntry();
throw new IOException("Failed to unzip flink python library.", e);
}
}
zis.closeEntry();
entry = zis.getNextEntry();
}
zis.closeEntry();
}
}
public void pushJarFile(URL jarfile, Predicate<ZipEntry> filter, Predicate<String> needTransform) throws IOException {
try (ZipInputStream input = new ZipInputStream(IOHelper.newInput(jarfile))) {
ZipEntry e = input.getNextEntry();
while (e != null) {
String filename = e.getName();
if (e.isDirectory() || fileList.contains(filename) || filter.test(e)) {
e = input.getNextEntry();
continue;
}
try {
output.putNextEntry(IOHelper.newZipEntry(e));
} catch (ZipException ex) {
LogHelper.warning("Write %s failed: %s", filename, ex.getMessage() == null ? "null" : ex.getMessage());
e = input.getNextEntry();
continue;
}
if (filename.endsWith(".class")) {
String classname = filename.replace('/', '.').substring(0,
filename.length() - ".class".length());
if (!needTransform.test(classname)) {
IOHelper.transfer(input, output);
} else {
byte[] bytes = IOHelper.read(input);
bytes = task.transformClass(bytes, classname, this);
output.write(bytes);
}
} else
IOHelper.transfer(input, output);
fileList.add(filename);
e = input.getNextEntry();
}
}
}
private void addEntry(List<ResourceFile> list, File zipFile, ZipEntry entry) {
if (entry.isDirectory()) {
return;
}
String name = entry.getName();
ResourceType type = ResourceType.getFileType(name);
ResourceFile rf = ResourceFile.createResourceFile(jadxRef, name, type);
if (rf != null) {
rf.setZipRef(new ZipRef(zipFile, name));
list.add(rf);
}
}
@Override
public Void call() throws InterruptedException, IOException {
try {
Enumeration<? extends ZipEntry> entries = in.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
// Since these entries come from an existing zip file, they should always know their size
// (meaning, never return -1). We also can't handle files that don't fit into a byte array.
checkArgument(entry.getSize() >= 0, "Cannot process entry with unknown size: %s", entry);
checkArgument(entry.getSize() <= Integer.MAX_VALUE, "Entry too large: %s", entry);
byte[] content;
if (entry.getSize() == 0L) {
content = EMPTY; // this in particular covers directory entries
} else {
try (InputStream entryStream = in.getInputStream(entry)) {
// Read all the content at once, which avoids temporary arrays and extra array copies
content = new byte[(int) entry.getSize()];
ByteStreams.readFully(entryStream, content); // throws if file is smaller than expected
checkState(entryStream.read() == -1,
"Too many bytes in jar entry %s, expected %s", entry, entry.getSize());
}
}
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
files.put(toDex(entry, content));
} else {
// Copy other files and directory entries
if (entry.getCompressedSize() != 0) {
entry.setCompressedSize(-1L); // We may compress differently from source Zip
}
files.put(immediateFuture(new ZipEntryContent(entry, content)));
}
}
} finally {
// Use try-finally to make absolutely sure we do this, otherwise the reader might deadlock
files.put(immediateFuture((ZipEntryContent) null)); // "end of stream" marker
}
return null;
}
/**
* Unzip a zip file into a directory.
* @param zipFile The zip file to be unzipped.
* @param dest the destination directory.
* @throws IOException if the destination does not exist or is not a directory, or if the zip file cannot be extracted.
*/
public static void unzip(ZipFile zipFile, File dest) throws IOException {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
if (dest.exists() && dest.isDirectory()) {
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
File destFile = new File(dest, entry.getName());
createFileWithPath(destFile);
InputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile))) {
byte[] buffer = new byte[2048];
for (;;) {
int nBytes = in.read(buffer);
if (nBytes <= 0)
break;
out.write(buffer, 0, nBytes);
}
out.flush();
}
in.close();
}
}
} else {
throw new IOException("Destination " + dest.getAbsolutePath() + " is not a directory or does not exist");
}
}
/**
* Returns true if a document within an archive is a child or any descendant of the archive
* document or another document within the archive.
*
*/
public boolean isChildDocument(String parentDocumentId, String documentId) {
final ParsedDocumentId parsedParentId = ParsedDocumentId.fromDocumentId(
parentDocumentId, mIdDelimiter);
final ParsedDocumentId parsedId = ParsedDocumentId.fromDocumentId(
documentId, mIdDelimiter);
Preconditions.checkArgumentEquals(mDocumentId, parsedParentId.mArchiveId,
"Mismatching document ID. Expected: %s, actual: %s.");
Preconditions.checkArgumentNotNull(parsedId.mPath,
"Not a document within an archive.");
final ZipEntry entry = mEntries.get(parsedId.mPath);
if (entry == null) {
return false;
}
if (parsedParentId.mPath == null) {
// No need to compare paths. Every file in the archive is a child of the archive
// file.
return true;
}
final ZipEntry parentEntry = mEntries.get(parsedParentId.mPath);
if (parentEntry == null || !parentEntry.isDirectory()) {
return false;
}
final String parentPath = entry.getName();
// Add a trailing slash even if it's not a directory, so it's easy to check if the
// entry is a descendant.
final String pathWithSlash = entry.isDirectory() ? entry.getName() : entry.getName() + "/";
return pathWithSlash.startsWith(parentPath) && !parentPath.equals(pathWithSlash);
}
static void optimize(final File f) throws IOException {
if (nodebug && f.getName().contains("debug")) {
return;
}
if (f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; ++i) {
optimize(files[i]);
}
} else if (f.getName().endsWith(".jar")) {
File g = new File(f.getParentFile(), f.getName() + ".new");
ZipFile zf = new ZipFile(f);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(g));
Enumeration<? extends ZipEntry> e = zf.entries();
byte[] buf = new byte[10000];
while (e.hasMoreElements()) {
ZipEntry ze = e.nextElement();
if (ze.isDirectory()) {
out.putNextEntry(ze);
continue;
}
out.putNextEntry(ze);
if (ze.getName().endsWith(".class")) {
ClassReader cr = new ClassReader(zf.getInputStream(ze));
// cr.accept(new ClassDump(), 0);
cr.accept(new ClassVerifier(), 0);
}
InputStream is = zf.getInputStream(ze);
int n;
do {
n = is.read(buf, 0, buf.length);
if (n != -1) {
out.write(buf, 0, n);
}
} while (n != -1);
out.closeEntry();
}
out.close();
zf.close();
if (!f.delete()) {
throw new IOException("Cannot delete file " + f);
}
if (!g.renameTo(f)) {
throw new IOException("Cannot rename file " + g);
}
}
}
/**
* Read a map from the given data file.
*
* @param dataFile
* File to read from.
* @return Map of class names to their bytecode.
* @throws InvalidJarException
*/
private static Map<String, byte[]> readClasses(File jar) throws IOException, InvalidJarException {
Map<String, byte[]> contents = new HashMap<>();
boolean found = false;
try (ZipFile file = new ZipFile(jar)) {
// iterate zip entries
Enumeration<? extends ZipEntry> entries = file.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
// skip directories
if (entry.isDirectory()) continue;
// skip non-classes (Deobfuscator doesn't have any resources aside for META)
String name = entry.getName();
if (!name.endsWith(".class")) {
continue;
}
try (InputStream is = file.getInputStream(entry)) {
// skip non-classes (Deobfuscator doesn't have any resources aside for
// META, which we will bundle to appease SLF4J's ServiceLoader screwery.)
byte[] value = from(is);
String className;
try
{
className = new MiniClassReader(value).getClassName();
}catch(Exception e)
{
continue;
}
// We know this class is in the deobfuscator jar, so if the jar does
// not contain it, it is not the correct file.
if (className.contains("com/javadeobfuscator/deobfuscator/Deobfuscator")) {
found = true;
}
contents.put(className.replace("/", "."), value);
}
}
}
// check to ensure expected content of jar file
if (!found) {
throw new InvalidJarException();
}
return contents;
}
protected void addAllResources(InputStream archive, String path, int notifyOption) {
ZipInputStream zipStream = new ZipInputStream(archive);
ZipEntry entry;
String contentType;
if (path.charAt(0) == '/') {
path = path.substring(1);
}
if (!path.endsWith("/")) {
path = path + "/";
}
try {
while((entry = zipStream.getNextEntry()) != null) {
Map resourceProps = new HashMap();
contentType = new MimetypesFileTypeMap().getContentType(entry.getName());
String title = entry.getName();
if (title.lastIndexOf("/") > 0) {
title = title.substring(title.lastIndexOf("/") + 1);
}
resourceProps.put(ResourceProperties.PROP_DISPLAY_NAME, title);
resourceProps.put(ResourceProperties.PROP_COPYRIGHT, COPYRIGHT);
if(log.isDebugEnabled()) {
log.debug("import ResourcesHandler about to add file entitled '{}'", title);
}
int count;
ByteArrayOutputStream contents = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER];
while ((count = zipStream.read(data, 0, BUFFER)) != -1) {
contents.write(data, 0, count);
}
if (entry.isDirectory()) {
addContentCollection(path + entry.getName(), resourceProps);
addAllResources(new ByteArrayInputStream(contents.toByteArray()), path + entry.getName(), notifyOption);
}
else {
addContentResource(path + entry.getName(), contentType, new ByteArrayInputStream(contents.toByteArray()), resourceProps, notifyOption);
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
public static boolean isJarDirectory(JarURLConnection conn) throws IOException {
JarFile jarFile = conn.getJarFile();
String entryName = conn.getEntryName();
ZipEntry dirEntry = jarFile.getEntry(addEndingSlash(entryName));
return dirEntry != null && dirEntry.isDirectory();
}