java.util.zip.ZipEntry#getSize ( )源码实例Demo

下面列出了java.util.zip.ZipEntry#getSize ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: beam   文件: ZipFilesTest.java
@Test
public void testAsByteSource() throws Exception {
  File zipDir = new File(tmpDir, "zip");
  assertTrue(zipDir.mkdirs());
  createFileWithContents(zipDir, "myTextFile.txt", "Simple Text");

  ZipFiles.zipDirectory(tmpDir, zipFile);

  try (ZipFile zip = new ZipFile(zipFile)) {
    ZipEntry entry = zip.getEntry("zip/myTextFile.txt");
    ByteSource byteSource = ZipFiles.asByteSource(zip, entry);
    if (entry.getSize() != -1) {
      assertEquals(entry.getSize(), byteSource.size());
    }
    assertArrayEquals("Simple Text".getBytes(StandardCharsets.UTF_8), byteSource.read());
  }
}
 
源代码2 项目: pentaho-reporting   文件: ZipContentLocation.java
public ZipContentLocation( ZipRepository repository, ZipContentLocation parent, ZipEntry zipEntry ) {
  if ( repository == null ) {
    throw new NullPointerException();
  }
  if ( parent == null ) {
    throw new NullPointerException();
  }
  if ( zipEntry == null ) {
    throw new NullPointerException();
  }

  this.repository = repository;
  this.parent = parent;
  this.entryName = IOUtils.getInstance().getFileName( zipEntry.getName() );
  this.comment = zipEntry.getComment();
  this.size = zipEntry.getSize();
  this.time = zipEntry.getTime();
  this.entries = new HashMap();
  this.name = RepositoryUtilities.buildName( this, "/" ) + '/';
}
 
源代码3 项目: Box   文件: ZipSecurity.java
public static boolean isZipBomb(ZipEntry entry) {
	long compressedSize = entry.getCompressedSize();
	long uncompressedSize = entry.getSize();
	if (compressedSize < 0 || uncompressedSize < 0) {
		LOG.error("Zip bomb attack detected, invalid sizes: compressed {}, uncompressed {}, name {}",
				compressedSize, uncompressedSize, entry.getName());
		return true;
	}
	if (compressedSize * MAX_SIZE_DIFF < uncompressedSize) {
		LOG.error("Zip bomb attack detected, invalid sizes: compressed {}, uncompressed {}, name {}",
				compressedSize, uncompressedSize, entry.getName());
		return true;
	}
	return false;
}
 
源代码4 项目: baratine   文件: JarWithStream.java
private ZipEntry getZipEntryImpl(String path)
  throws IOException
{
  if (path.startsWith("/")) {
    path = path.substring(1);
  }
  
  try (InputStream is = getBacking().openRead()) {
    try (ZipInputStream zIn = new ZipInputStream(is)) {
      ZipEntry entry;

      while ((entry = zIn.getNextEntry()) != null) {
        if (entry.getName().equals(path)) {
          ZipEntry entryResult = new ZipEntry(entry);
          
          if (entry.getSize() < 0 && ! entry.isDirectory()) {
            long size = 0;
            TempBuffer tBuf = TempBuffer.create();
            byte []buffer = tBuf.buffer();
            
            int sublen;
            while ((sublen = zIn.read(buffer, 0, buffer.length)) > 0) {
              size += sublen;
            }
            
            tBuf.free();
            
            entryResult.setSize(size);
          }
          
          return entryResult;
        }
      }
    }
  }
  
  return null;
}
 
源代码5 项目: netbeans   文件: FileObjects.java
@Override
protected long getSize () throws IOException {
    ZipFile zf = new ZipFile (archiveFile);
    try {
        ZipEntry ze = zf.getEntry(this.resName);
        return ze == null ? 0L : ze.getSize();
    } finally {
        zf.close();
    }
}
 
源代码6 项目: android_9.0.0_r45   文件: StrictJarFile.java
private InputStream getZipInputStream(ZipEntry ze) {
    if (ze.getMethod() == ZipEntry.STORED) {
        return new FDStream(fd, ze.getDataOffset(),
                ze.getDataOffset() + ze.getSize());
    } else {
        final FDStream wrapped = new FDStream(
                fd, ze.getDataOffset(), ze.getDataOffset() + ze.getCompressedSize());

        int bufSize = Math.max(1024, (int) Math.min(ze.getSize(), 65535L));
        return new ZipInflaterInputStream(wrapped, new Inflater(true), bufSize, ze);
    }
}
 
源代码7 项目: rxjava2-extras   文件: ZippedEntry.java
public ZippedEntry(ZipEntry e, InputStream is) {
    this.name = e.getName();
    this.time = e.getTime();
    // this.mtime = e.getLastModifiedTime();
    // this.atime = e.getLastAccessTime();
    // this.ctime = e.getCreationTime();
    this.crc = e.getCrc();
    this.size = e.getSize();
    this.csize = e.getCompressedSize();
    this.method = e.getMethod();
    this.extra = e.getExtra();
    this.comment = e.getComment();
    this.is = is;
}
 
源代码8 项目: dragonwell8_jdk   文件: Utils.java
static String zeString(ZipEntry ze) {
    int store = (ze.getCompressedSize() > 0) ?
        (int)( (1.0 - ((double)ze.getCompressedSize()/(double)ze.getSize()))*100 )
        : 0 ;
    // Follow unzip -lv output
    return ze.getSize() + "\t" + ze.getMethod()
        + "\t" + ze.getCompressedSize() + "\t"
        + store + "%\t"
        + new Date(ze.getTime()) + "\t"
        + Long.toHexString(ze.getCrc()) + "\t"
        + ze.getName() ;
}
 
源代码9 项目: jolie   文件: JapURLConnection.java
@Override
public void connect()
	throws IOException {
	if( !connected ) {
		final String urlPath = url.getPath();
		final Matcher matcher = URL_PATTERN.matcher( urlPath );
		if( matcher.matches() ) {
			final String path = matcher.group( 1 );
			final String subPath = matcher.group( 2 );
			final JarURLConnection jarURLConnection = (JarURLConnection) new URL( "jar:" + path ).openConnection();
			inputStream = jarURLConnection.getInputStream();
			if( subPath.isEmpty() == false ) {
				JarFile jar = retrieve( new URL( path ), inputStream );
				final String[] nodes = NESTING_SEPARATION_PATTERN.split( subPath );
				int i;
				final StringBuilder builder = new StringBuilder( path.length() + subPath.length() );
				builder.append( path );
				for( i = 0; i < nodes.length - 1; i++ ) {
					builder.append( "!/" ).append( nodes[ i ] );
					jar = retrieve( new URL( builder.toString() ), inputStream );
				}
				final ZipEntry entry = jar.getEntry( nodes[ i ] );
				entrySize = entry.getSize();
				inputStream = jar.getInputStream( entry );
			}
		} else {
			throw new MalformedURLException( "Invalid JAP URL path: " + urlPath );
		}

		connected = true;
	}
}
 
源代码10 项目: bazel   文件: DexFileSplitter.java
private void processDexEntry(ZipFile zip, ZipEntry entry) throws IOException {
  String filename = entry.getName();
  checkState(filename.endsWith(".class.dex"),
      "%s isn't a dex archive: %s", zip.getName(), filename);
  checkState(entry.getMethod() == ZipEntry.STORED, "Expect to process STORED: %s", filename);
  if (inCoreLib == null) {
    inCoreLib = filename.startsWith("j$/");
  } else if (inCoreLib != filename.startsWith("j$/")) {
    // Put j$.xxx classes in separate file.  This shouldn't normally happen (b/134705306).
    nextShard();
    inCoreLib = !inCoreLib;
  }
  if (inCoreLib) {
    System.err.printf(
        "WARNING: Unexpected file %s found. Please ensure this only happens in test APKs.%n",
        filename);
  }

  try (InputStream entryStream = zip.getInputStream(entry)) {
    // We don't want to use the Dex(InputStream) constructor because it closes the stream,
    // which will break the for loop, and it has its own bespoke way of reading the file into
    // a byte buffer before effectively calling Dex(byte[]) anyway.
    // TODO(kmb) since entry is stored, mmap content and give to Dex(ByteBuffer) and output zip
    byte[] 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());

    Dex dexFile = new Dex(content);
    if (tracker.track(dexFile)) {
      nextShard();
      tracker.track(dexFile);
    }
    curOut.writeAsync(entry, content);
  }
}
 
源代码11 项目: openjdk-jdk8u-backup   文件: Utils.java
static String zeString(ZipEntry ze) {
    int store = (ze.getCompressedSize() > 0) ?
        (int)( (1.0 - ((double)ze.getCompressedSize()/(double)ze.getSize()))*100 )
        : 0 ;
    // Follow unzip -lv output
    return ze.getSize() + "\t" + ze.getMethod()
        + "\t" + ze.getCompressedSize() + "\t"
        + store + "%\t"
        + new Date(ze.getTime()) + "\t"
        + Long.toHexString(ze.getCrc()) + "\t"
        + ze.getName() ;
}
 
源代码12 项目: baratine   文件: JarWithFile.java
/**
 * Returns the length of the entry in the jar file.
 *
 * @param path full path to the jar entry
 * @return the length of the entry
 */
public long getLength(String path)
{
  try {
    ZipEntry entry = getZipEntry(path);

    long length = entry != null ? entry.getSize() : -1;
    
    return length;
  } catch (IOException e) {
    log.log(Level.FINE, e.toString(), e);
    
    return -1;
  }
}
 
源代码13 项目: rxjava-extras   文件: ZippedEntry.java
public ZippedEntry(ZipEntry e, InputStream is) {
    this.name = e.getName();
    this.time = e.getTime();
    // this.mtime = e.getLastModifiedTime();
    // this.atime = e.getLastAccessTime();
    // this.ctime = e.getCreationTime();
    this.crc = e.getCrc();
    this.size = e.getSize();
    this.csize = e.getCompressedSize();
    this.method = e.getMethod();
    this.extra = e.getExtra();
    this.comment = e.getComment();
    this.is = is;
}
 
源代码14 项目: java-client-api   文件: ZipSplitterTest.java
private void checkContent(ZipInputStream zipInputStream,
                          ZipEntry zipEntry,
                          String unzippedContent) throws Exception {

    byte[] originalFileBytes = new byte[(int) zipEntry.getSize()];
    zipInputStream.read(originalFileBytes, 0, originalFileBytes.length);
    String originalFileContent = new String(originalFileBytes);
    assertEquals(unzippedContent, originalFileContent);
}
 
源代码15 项目: netbeans   文件: JarClassLoader.java
@Override
public byte[] resource(String path) throws IOException {
    if (nonexistentResources.contains(path)) {
        return null;
    }
    JarFile jf;
    try {
        jf = getJarFile(path);
    } catch (ZipException ex) {
        if (warnedFiles.add(file)) {
            LOGGER.log(Level.INFO, "Cannot open " + file, ex);
            dumpFiles(file, -1);
        }
        return null;
    }
    try {
        ZipEntry ze = jf.getEntry(path);
        if (ze == null) {
            nonexistentResources.add(path);
            return null;
        }

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.log(Level.FINER, "Loading {0} from {1}", new Object[] {path, file.getPath()});
        }
    
        int len = (int)ze.getSize();
        byte[] data = new byte[len];
        InputStream is = jf.getInputStream(ze);
        int count = 0;
        while (count < len) {
            count += is.read(data, count, len-count);
        }
        return data;
    } finally {
        releaseJarFile();
    }
}
 
源代码16 项目: size-analyzer   文件: ProguardSuggester.java
@Override
public ImmutableList<Suggestion> processBundle(
    BundleContext context, AppBundle bundle, ZipFile bundleZip) {
  // Some old bundles contain multidex code in a way not compatible with the new AppBundle
  // representation, so the extraction of ZIP entries results in null pointers. Hence, entries are
  // wrapped in optionals to precisely capture the nulls.
  ImmutableList<Optional<ZipEntry>> dexFileEntries =
      bundle.getModules().values().stream()
          .flatMap(
              module ->
                  module
                      .findEntriesUnderPath(BundleModule.DEX_DIRECTORY)
                      .map(ModuleEntry::getPath)
                      .map(ZipPath.create(module.getName().toString())::resolve))
          .map(ZipPath::toString)
          .map(bundleZip::getEntry)
          .map(Optional::ofNullable)
          .collect(toImmutableList());

  OptionalLong totalDex =
      dexFileEntries.stream().anyMatch(not(Optional::isPresent))
          ? OptionalLong.empty()
          : OptionalLong.of(
              dexFileEntries.stream().map(Optional::get).mapToLong(ZipEntry::getSize).sum());

  ZipEntry proguardEntry = bundleZip.getEntry(PROGUARD_MAP);

  if (proguardEntry == null) {
    return ImmutableList.of(
        Suggestion.create(
            IssueType.PROGUARD_NO_MAP,
            Category.PROGUARD,
            totalDexPayload(totalDex),
            NO_MAP_SUGGESTION_MESSAGE,
            /* estimatedBytesSaved= */ null,
            /* autoFix= */ null));
  }

  // Deobfuscation map present.
  if (proguardEntry.getSize() == 0) {
    // Empty deobfuscation map.
    return ImmutableList.of(
        Suggestion.create(
            IssueType.PROGUARD_EMPTY_MAP,
            Category.PROGUARD,
            totalDexPayload(totalDex),
            EMPTY_MAP_SUGGESTION_MESSAGE,
            /* estimatedBytesSaved= */ null,
            /* autoFix= */ null));
  }

  // Everything is fine with the map, no suggestions.
  return ImmutableList.of();
}
 
源代码17 项目: visualvm   文件: ClassFileCache.java
private byte[] readClassFile(String name, String classFileLocation)
                      throws IOException {
    String classFileName = name + ".class"; // NOI18N
    File location = new File(classFileLocation);

    if (location.isDirectory()) {
        return MiscUtils.readFileIntoBuffer(new FileOrZipEntry(classFileLocation, classFileName));
    } else { // Should be .jar file
             // The following code may be used at different stages of JFluid work, with different initialization states, so
             // it's coded defensively. If it can use an available open ZipFile, it will use it, otherwise it will open its own.

        ZipFile zip = null;

        if (classPath == null) {
            classPath = ClassRepository.getClassPath();
        }

        if (classPath != null) {
            try {
                zip = classPath.getZipFileForName(classFileLocation);
            } catch (ZipException e2) {
                throw new IOException("Could not open archive " + classFileLocation); // NOI18N
            }
        } else {
            throw new IOException("Could not get classpath for " + classFileName + " in " + classFileLocation); // NOI18N
        }

        ZipEntry entry = zip.getEntry(classFileName);

        if (entry == null) {
            throw new IOException("Could not find entry for " + classFileName + " in " + classFileLocation); // NOI18N
        }

        int len = (int) entry.getSize();
        byte[] buf = new byte[len];
        InputStream in = zip.getInputStream(entry);
        int readBytes;
        int ofs = 0;
        int remBytes = len;

        do {
            readBytes = in.read(buf, ofs, remBytes);
            ofs += readBytes;
            remBytes -= readBytes;
        } while (ofs < len);

        in.close();

        return buf;
    }
}
 
源代码18 项目: BlogSystem   文件: BloggerBlogServiceImpl.java
private BlogTitleIdDTO analysisAndInsertMdFile(Parser parser, HtmlRenderer renderer, ZipEntry entry,
                                               InputStreamReader reader, int bloggerId, Long cateId) throws IOException {
    String name = entry.getName();

    if (!name.endsWith(".md")) return null;

    StringBuilder b = new StringBuilder((int) entry.getSize());
    int len = 0;
    char[] buff = new char[1024];
    while ((len = reader.read(buff)) > 0) {
        b.append(buff, 0, len);
    }

    // reader.close();
    // zip 文件关闭由 370行:zipFile.close() 统一关闭

    // 内容
    String mdContent = b.toString();

    // 对应的 html 内容
    Document document = parser.parse(mdContent);
    String htmlContent = renderer.render(document);

    // 摘要
    String firReg = htmlContent.replaceAll("<.*?>", ""); // 避免 subString 使有遗留的 html 标签,前端显示时会出错
    String tmpStr = firReg.length() > 500 ? firReg.substring(0, 500) : firReg;
    String aftReg = tmpStr.replaceAll("\\n", "");
    String summary = aftReg.length() > 200 ? aftReg.substring(0, 200) : aftReg;

    // UPDATE: 2018/4/4 更新 图片引用

    // 文件名作为标题
    String title = cateId == -1 ? name.replace(".md", "") :
            name.substring(name.lastIndexOf("/") + 1).replace(".md", "");

    int[] cts = {Math.toIntExact(cateId)};
    int id = insertBlog(bloggerId,
            cts,
            null,
            PUBLIC,
            title,
            htmlContent,
            mdContent,
            summary,
            null,
            false);
    if (id < 0) return null;

    BlogTitleIdDTO node = new BlogTitleIdDTO();
    node.setTitle(title);
    node.setId(id);

    return node;
}
 
源代码19 项目: ratel   文件: ZipRODirectory.java
@Override
public long getSize(String fileName)
        throws DirectoryException {
    ZipEntry entry = getZipFileEntry(fileName);
    return entry.getSize();
}
 
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
    if (zipIn == null) {
        hasNext = false;
        return false;
    }

    ZipEntry zipEntry;
    ZipInputStream zis = (ZipInputStream) zipIn;
    if (value == null) {
        value = new DatabaseDocumentWithMeta();
    }
    while ((zipEntry = zis.getNextEntry()) != null) {
        subId = zipEntry.getName();
        long length = zipEntry.getSize();
        if (subId.endsWith(DocumentMetadata.NAKED)) {
            ((DatabaseDocumentWithMeta) value)
                .setMeta(getMetadataFromStream(length));
            String uri = subId.substring(0, subId.length()
                    - DocumentMetadata.NAKED.length());
            setKey(uri, 0, 0, false);
            value.setContent(null);
            count++;
            return true;
        }
        if (count % 2 == 0 && subId.endsWith(DocumentMetadata.EXTENSION)) {
            ((DatabaseDocumentWithMeta) value)
                .setMeta(getMetadataFromStream(length));
            count++;
            continue;
        }
        // no meta data
        if (count % 2 == 0 && !allowEmptyMeta) {
            setSkipKey(0, 0, "Missing metadata");
            return true;
        } else {
            setKey(subId, 0, 0, false);
            readDocFromStream(length, (DatabaseDocument) value);
            count++;
            return true;
        }
    }
    //end of a zip
    if (iterator != null && iterator.hasNext()) {
        close();
        initStream(iterator.next());
        return nextKeyValue();
    } else {
        hasNext = false;
        return false;
    }
}