Java 类java.util.zip.ZipException 实例源码

项目:litiengine    文件:GameFile.java   
private static GameFile getGameFileFromFile(String file) throws JAXBException, IOException {
  final JAXBContext jaxbContext = JAXBContext.newInstance(GameFile.class);
  final Unmarshaller um = jaxbContext.createUnmarshaller();
  try (InputStream inputStream = FileUtilities.getGameResource(file)) {

    // try to get compressed game file
    final GZIPInputStream zipStream = new GZIPInputStream(inputStream);
    return (GameFile) um.unmarshal(zipStream);
  } catch (final ZipException e) {

    // if it fails to load the compressed file, get it from plain XML
    InputStream stream = null;
    stream = FileUtilities.getGameResource(file);
    if (stream == null) {
      return null;
    }

    return (GameFile) um.unmarshal(stream);
  }
}
项目:openjdk-jdk10    文件:ZipFileSystemProvider.java   
@Override
public FileSystem newFileSystem(Path path, Map<String, ?> env)
    throws IOException
{
    if (path.getFileSystem() != FileSystems.getDefault()) {
        throw new UnsupportedOperationException();
    }
    ensureFile(path);
     try {
         ZipFileSystem zipfs;
         if (env.containsKey("multi-release")) {
             zipfs = new JarFileSystem(this, path, env);
         } else {
             zipfs = new ZipFileSystem(this, path, env);
         }
        return zipfs;
    } catch (ZipException ze) {
        String pname = path.toString();
        if (pname.endsWith(".zip") || pname.endsWith(".jar"))
            throw ze;
        throw new UnsupportedOperationException();
    }
}
项目:openjdk-jdk10    文件:ZipFileSystem.java   
EntryInputStream(Entry e, SeekableByteChannel zfch)
    throws IOException
{
    this.zfch = zfch;
    rem = e.csize;
    size = e.size;
    pos = e.locoff;
    if (pos == -1) {
        Entry e2 = getEntry(e.name);
        if (e2 == null) {
            throw new ZipException("invalid loc for entry <" + e.name + ">");
        }
        pos = e2.locoff;
    }
    pos = -pos;  // lazy initialize the real data offset
}
项目:ObsidianSuite    文件:ImporterQubble.java   
private QubbleModel load(File file) throws IOException
{
    try (ZipFile zipFile = new ZipFile(file))
    {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements())
        {
            ZipEntry entry = entries.nextElement();

            if (entry.getName().equals("model.nbt"))
            {
                NBTTagCompound compound = CompressedStreamTools.read(new DataInputStream(zipFile.getInputStream(entry)));
                return QubbleModel.deserialize(compound);
            }
        }
    }
    catch (ZipException zipException)
    {
        return this.loadLegacy(file);
    }

    return null;
}
项目:openjdk-jdk10    文件:InputFilesTest.java   
private void jar(String cmdline) throws IOException {
    System.out.println("jar " + cmdline);
    baos.reset();

    // the run method catches IOExceptions, we need to expose them
    ByteArrayOutputStream baes = new ByteArrayOutputStream();
    PrintStream err = new PrintStream(baes);
    PrintStream saveErr = System.err;
    System.setErr(err);
    int rc = JAR_TOOL.run(out, err, cmdline.split(" +"));
    System.setErr(saveErr);
    if (rc != 0) {
        String s = baes.toString();
        if (s.startsWith("java.util.zip.ZipException: duplicate entry: ")) {
            throw new ZipException(s);
        }
        throw new IOException(s);
    }
}
项目:letv    文件:ZipUtil.java   
static CentralDirectory findCentralDirectory(RandomAccessFile raf) throws IOException, ZipException {
    long scanOffset = raf.length() - 22;
    if (scanOffset < 0) {
        throw new ZipException("File too short to be a zip file: " + raf.length());
    }
    long stopOffset = scanOffset - 65536;
    if (stopOffset < 0) {
        stopOffset = 0;
    }
    int endSig = Integer.reverseBytes(ENDSIG);
    do {
        raf.seek(scanOffset);
        if (raf.readInt() == endSig) {
            raf.skipBytes(2);
            raf.skipBytes(2);
            raf.skipBytes(2);
            raf.skipBytes(2);
            CentralDirectory dir = new CentralDirectory();
            dir.size = ((long) Integer.reverseBytes(raf.readInt())) & 4294967295L;
            dir.offset = ((long) Integer.reverseBytes(raf.readInt())) & 4294967295L;
            return dir;
        }
        scanOffset--;
    } while (scanOffset >= stopOffset);
    throw new ZipException("End Of Central Directory signature not found");
}
项目:Equella    文件:CalConfigPanel.java   
@Override
public final void exception()
{
    Exception ex = getException();
    if( ex instanceof BannedFileException )
    {
        Driver.displayInformation(getComponent(), "File upload cancelled.  File extension has been banned.");
    }
    else if( ex instanceof FileNotFoundException )
    {
        Driver.displayError(getComponent(), "displayTemplate/readingXSLT", ex); //$NON-NLS-1$
        LOGGER.error("Error opening XSLT or clearing staging", ex);
    }
    else if( ex instanceof ZipException )
    {
        Driver.displayError(getComponent(), "displayTemplate/unzippingXSLT", ex); //$NON-NLS-1$
        LOGGER.error("Error unzippig XSLT", ex);
    }
    else
    {
        Driver.displayError(getComponent(), "displayTemplate/uploadingXSLT", ex); //$NON-NLS-1$
        LOGGER.error("Error uploading XSLT", ex);
    }
}
项目:Equella    文件:CLAConfigPanel.java   
@Override
public final void exception()
{
    Exception ex = getException();
    if( ex instanceof BannedFileException )
    {
        Driver.displayInformation(getComponent(), "File upload cancelled.  File extension has been banned.");
    }
    else if( ex instanceof FileNotFoundException )
    {
        Driver.displayError(getComponent(), "displayTemplate/readingXSLT", ex); //$NON-NLS-1$
        LOGGER.error("Error opening XSLT or clearing staging", ex);
    }
    else if( ex instanceof ZipException )
    {
        Driver.displayError(getComponent(), "displayTemplate/unzippingXSLT", ex); //$NON-NLS-1$
        LOGGER.error("Error unzippig XSLT", ex);
    }
    else
    {
        Driver.displayError(getComponent(), "displayTemplate/uploadingXSLT", ex); //$NON-NLS-1$
        LOGGER.error("Error uploading XSLT", ex);
    }
}
项目:javaide    文件:ZipFileIndex.java   
private byte[] readBytes(Entry entry) throws IOException {
    byte[] header = getHeader(entry);
    int csize = entry.compressedSize;
    byte[] cbuf = new byte[csize];
    zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
    zipRandomFile.readFully(cbuf, 0, csize);

    // is this compressed - offset 8 in the ZipEntry header
    if (get2ByteLittleEndian(header, 8) == 0)
        return cbuf;

    int size = entry.size;
    byte[] buf = new byte[size];
    if (inflate(cbuf, buf) != size)
        throw new ZipException("corrupted zip file");

    return buf;
}
项目:OpenJSharp    文件:ZipFileIndex.java   
private byte[] readBytes(Entry entry) throws IOException {
    byte[] header = getHeader(entry);
    int csize = entry.compressedSize;
    byte[] cbuf = new byte[csize];
    zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
    zipRandomFile.readFully(cbuf, 0, csize);

    // is this compressed - offset 8 in the ZipEntry header
    if (get2ByteLittleEndian(header, 8) == 0)
        return cbuf;

    int size = entry.size;
    byte[] buf = new byte[size];
    if (inflate(cbuf, buf) != size)
        throw new ZipException("corrupted zip file");

    return buf;
}
项目:OpenJSharp    文件:ZipFileSystem.java   
public void deleteFile(byte[] path, boolean failIfNotExists)
    throws IOException
{
    checkWritable();

    IndexNode inode = getInode(path);
    if (inode == null) {
        if (path != null && path.length == 0)
            throw new ZipException("root directory </> can't not be delete");
        if (failIfNotExists)
            throw new NoSuchFileException(getString(path));
    } else {
        if (inode.isDir() && inode.child != null)
            throw new DirectoryNotEmptyException(getString(path));
        updateDelete(inode);
    }
}
项目:OpenJSharp    文件:ZipFileSystem.java   
@Override
public void write(byte b[], int off, int len) throws IOException {
    if (e.type != Entry.FILECH)    // only from sync
        ensureOpen();
    if (off < 0 || len < 0 || off > b.length - len) {
        throw new IndexOutOfBoundsException();
    } else if (len == 0) {
        return;
    }
    switch (e.method) {
    case METHOD_DEFLATED:
        super.write(b, off, len);
        break;
    case METHOD_STORED:
        written += len;
        out.write(b, off, len);
        break;
    default:
        throw new ZipException("invalid compression method");
    }
    crc.update(b, off, len);
}
项目:openjdk-jdk10    文件:ZipFileSystem.java   
public void deleteFile(byte[] path, boolean failIfNotExists)
    throws IOException
{
    checkWritable();

    IndexNode inode = getInode(path);
    if (inode == null) {
        if (path != null && path.length == 0)
            throw new ZipException("root directory </> can't not be delete");
        if (failIfNotExists)
            throw new NoSuchFileException(getString(path));
    } else {
        if (inode.isDir() && inode.child != null)
            throw new DirectoryNotEmptyException(getString(path));
        updateDelete(inode);
    }
}
项目:boohee_v5.6    文件:ZipUtil.java   
static CentralDirectory findCentralDirectory(RandomAccessFile raf) throws IOException, ZipException {
    long scanOffset = raf.length() - 22;
    if (scanOffset < 0) {
        throw new ZipException("File too short to be a zip file: " + raf.length());
    }
    long stopOffset = scanOffset - 65536;
    if (stopOffset < 0) {
        stopOffset = 0;
    }
    int endSig = Integer.reverseBytes(ENDSIG);
    do {
        raf.seek(scanOffset);
        if (raf.readInt() == endSig) {
            raf.skipBytes(2);
            raf.skipBytes(2);
            raf.skipBytes(2);
            raf.skipBytes(2);
            CentralDirectory dir = new CentralDirectory();
            dir.size = ((long) Integer.reverseBytes(raf.readInt())) & 4294967295L;
            dir.offset = ((long) Integer.reverseBytes(raf.readInt())) & 4294967295L;
            return dir;
        }
        scanOffset--;
    } while (scanOffset >= stopOffset);
    throw new ZipException("End Of Central Directory signature not found");
}
项目:BaseCore    文件:ZipUtils.java   
/**
 * 获得压缩文件内文件列表
 *
 * @param zipFile 压缩文件
 * @return 压缩文件内文件名称
 * @throws ZipException 压缩文件格式有误时抛出
 * @throws IOException  当解压缩过程出错时抛出
 */
public static ArrayList<String> getEntriesNames(File zipFile) throws ZipException, IOException {
    ArrayList<String> entryNames = new ArrayList<String>();
    Enumeration<?> entries = getEntriesEnumeration(zipFile);
    while (entries.hasMoreElements()) {
        ZipEntry entry = ((ZipEntry) entries.nextElement());
        entryNames.add(new String(getEntryName(entry).getBytes("GB2312"), "8859_1"));
    }
    return entryNames;
}
项目:openNaEF    文件:SimulationEntryImpl.java   
@Override
public boolean exists() throws IOException, ZipException {
    ZipFile zip = new ZipFile(this.archive.getSimulationArchiveFile());
    ZipEntry entry = zip.getEntry(targetId + "/");
    if (entry != null) {
        return true;
    }
    return false;
}
项目:GitHub    文件:TinkerZipFile.java   
static void throwZipException(String filename, long fileSize, String entryName, long localHeaderRelOffset, String msg, int magic) throws ZipException {
    final String hexString = Integer.toHexString(magic);
    throw new ZipException("file name:" + filename
                           + ", file size" + fileSize
                           + ", entry name:" + entryName
                           + ", entry localHeaderRelOffset:" + localHeaderRelOffset
                           + ", "
                           + msg + " signature not found; was " + hexString);
}
项目:jdk8u-jdk    文件:ZipFileSystem.java   
private long getDataPos(Entry e) throws IOException {
    if (e.locoff == -1) {
        Entry e2 = getEntry0(e.name);
        if (e2 == null)
            throw new ZipException("invalid loc for entry <" + e.name + ">");
        e.locoff = e2.locoff;
    }
    byte[] buf = new byte[LOCHDR];
    if (readFullyAt(buf, 0, buf.length, e.locoff) != buf.length)
        throw new ZipException("invalid loc for entry <" + e.name + ">");
    return locpos + e.locoff + LOCHDR + LOCNAM(buf) + LOCEXT(buf);
}
项目:n4js    文件:ECMA6TestSuite.java   
/**
 * Generates collection of ZipEntry instances that will be used as data provided parameter is mapped to name of the
 * test (takes advantage of fact that ZipEntry.toString() is the same as entry.getName())
 *
 * @see TestCodeProvider#getDataFromZippedRoot(String, JSLibSingleTestConfigProvider)
 * @return a collection of pairs {@link ZipEntry} -> blacklist
 */
@Parameters(name = "{0}")
public static Collection<JSLibSingleTestConfig> data() throws URISyntaxException, ZipException, IOException {
    return TestCodeProvider.getDataFromZippedRoots(ECMASCRIPT_TEST_SUITE_ARCHIVE,
            new ECMAScriptSingleTestConfigProvider(
                    REQUIRE_VALIDATOR_FILENAME,
                    REQUIRE_VALIDATOR_TODO_FILENAME,
                    BLACKLIST_FILENAME,
                    BLACKLIST_EXECUTION_FILENAME, BLACKLIST_STRICT_MODE_FILENAME));
}
项目:n4js    文件:ECMA5TestSuite.java   
/**
 * Generates collection of ZipEntry instances that will be used as data provided parameter is mapped to name of the
 * test (takes advantage of fact that ZipEntry.toString() is the same as entry.getName())
 *
 * @see TestCodeProvider#getDataFromZippedRoot(String, JSLibSingleTestConfigProvider)
 * @return a collection of pairs {@link ZipEntry} -> blacklist
 */
@Parameters(name = "{0}")
public static Collection<JSLibSingleTestConfig> data() throws URISyntaxException, ZipException, IOException {
    return TestCodeProvider.getDataFromZippedRoots(ECMASCRIPT_TEST_SUITE_ARCHIVE,
            new ECMAScriptSingleTestConfigProvider(
                    REQUIRE_VALIDATOR_FILENAME,
                    REQUIRE_VALIDATOR_TODO_FILENAME,
                    BLACKLIST_FILENAME,
                    BLACKLIST_EXECUTION_FILENAME, BLACKLIST_STRICT_MODE_FILENAME));
}
项目:openjdk-jdk10    文件:ZipFileSystem.java   
@Override
public synchronized void close() throws IOException {
    if (isClosed) {
        return;
    }
    isClosed = true;
    // TBD ensureOpen();
    switch (e.method) {
    case METHOD_DEFLATED:
        finish();
        e.size  = def.getBytesRead();
        e.csize = def.getBytesWritten();
        e.crc = crc.getValue();
        break;
    case METHOD_STORED:
        // we already know that both e.size and e.csize are the same
        e.size = e.csize = written;
        e.crc = crc.getValue();
        break;
    default:
        throw new ZipException("invalid compression method");
    }
    //crc.reset();
    if (out instanceof ByteArrayOutputStream)
        e.bytes = ((ByteArrayOutputStream)out).toByteArray();

    if (e.type == Entry.FILECH) {
        releaseDeflater(def);
        return;
    }
    super.close();
    releaseDeflater(def);
    update(e);
}
项目:incubator-netbeans    文件:GlobalSourceForBinaryImpl.java   
/**
 * May return <code>null</code> if the given zip is not a valid
 * NetBeans sources zip.
 */
public static NetBeansSourcesParser getInstance(File nbSrcZip) throws ZipException, IOException {
    NetBeansSourcesParser nbsp = instances.get(nbSrcZip);
    if (nbsp == null) {
        ZipFile nbSrcZipFile = new ZipFile(nbSrcZip);
        String zipNBRoot = NetBeansSourcesParser.findNBRoot(nbSrcZipFile);
        if (zipNBRoot != null) {
            nbsp = new NetBeansSourcesParser(nbSrcZipFile, zipNBRoot);
            instances.put(nbSrcZip, nbsp);
        }
    }
    return nbsp;
}
项目:framework    文件:InflaterInputStream.java   
/**
 * Reads uncompressed data into an array of bytes. If <code>len</code> is not
 * zero, the method will block until some input can be decompressed; otherwise,
 * no bytes are read and <code>0</code> is returned.
 *
 * @param b   the buffer into which the data is read
 * @param off the start offset in the destination array <code>b</code>
 * @param len the maximum number of bytes read
 * @return the actual number of bytes read, or -1 if the end of the
 * compressed input is reached or a preset dictionary is needed
 * @throws NullPointerException      If <code>b</code> is <code>null</code>.
 * @throws IndexOutOfBoundsException If <code>off</code> is negative,
 *                                   <code>len</code> is negative, or <code>len</code> is greater than
 *                                   <code>b.length - off</code>
 * @throws ZipException              if a ZIP format error has occurred
 * @throws IOException               if an I/O error has occurred
 */
public int read(byte[] b, int off, int len) throws IOException {
    ensureOpen();
    if (b == null) {
        throw new NullPointerException();
    } else if (off < 0 || len < 0 || len > b.length - off) {
        throw new IndexOutOfBoundsException();
    } else if (len == 0) {
        return 0;
    }
    try {
        int n;
        while ((n = inf.inflate(b, off, len)) == 0) {
            if (inf.finished() || inf.needsDictionary()) {
                reachEOF = true;
                return -1;
            }
            if (inf.needsInput()) {
                fill();
            }
        }
        return n;
    } catch (DataFormatException e) {
        String s = e.getMessage();
        throw new ZipException(s != null ? s : "Invalid ZLIB data format");
    }
}
项目:framework    文件:ZipOutputStream.java   
private static int version(ZipEntry e) throws ZipException {
    switch (e.method) {
        case DEFLATED:
            return 20;
        case STORED:
            return 10;
        default:
            throw new ZipException("unsupported compression method");
    }
}
项目:framework    文件:ZipOutputStream.java   
/**
 * Begins writing a new ZIP file entry and positions the stream to the
 * start of the entry data. Closes the current entry if still active.
 * The default compression method will be used if no compression method
 * was specified for the entry, and the current time will be used if
 * the entry has no set modification time.
 *
 * @param e the ZIP entry to be written
 * @throws ZipException if a ZIP format error has occurred
 * @throws IOException  if an I/O error has occurred
 */
public void putNextEntry(ZipEntry e) throws IOException {
    ensureOpen();
    if (current != null) {
        closeEntry();    // close previous entry
    }
    if (e.time == -1) {
        e.setTime(System.currentTimeMillis());
    }
    if (e.method == -1) {
        e.method = method;    // use default method
    }
    switch (e.method) {
        case DEFLATED:
            break;
        case STORED:
            // compressed size, uncompressed size, and crc-32 must all be
            // set for entries using STORED compression method
            if (e.size == -1) {
                e.size = e.csize;
            } else if (e.csize == -1) {
                e.csize = e.size;
            } else if (e.size != e.csize) {
                throw new ZipException("STORED entry where compressed != uncompressed size");
            }
            if (e.size == -1 || e.crc == -1) {
                throw new ZipException("STORED entry missing size, compressed size, or crc-32");
            }
            break;
        default:
            throw new ZipException("unsupported compression method");
    }
    if (!names.add(e.name)) {
        throw new ZipException("duplicate entry: " + e.name);
    }
    current = new XEntry(e, written);
    xentries.add(current);
    writeLOC(current);
}
项目:lazycat    文件:WARDirContext.java   
/**
 * Content accessor.
 * 
 * @return InputStream
 */
@Override
public InputStream streamContent() throws IOException {
    try {
        if (binaryContent == null) {
            InputStream is = base.getInputStream(entry);
            inputStream = is;
            return is;
        }
    } catch (ZipException e) {
        throw new IOException(e.getMessage(), e);
    }
    return super.streamContent();
}
项目:framework    文件:ZipOutputStream.java   
/**
 * Writes an array of bytes to the current ZIP entry data. This method
 * will block until all the bytes are written.
 *
 * @param b   the data to be written
 * @param off the start offset in the data
 * @param len the number of bytes that are written
 * @throws ZipException if a ZIP file error has occurred
 * @throws IOException  if an I/O error has occurred
 */
public synchronized void write(byte[] b, int off, int len) throws IOException {
    ensureOpen();
    if (off < 0 || len < 0 || off > b.length - len) {
        throw new IndexOutOfBoundsException();
    } else if (len == 0) {
        return;
    }

    if (current == null) {
        throw new ZipException("no current ZIP entry");
    }
    ZipEntry entry = current.entry;
    switch (entry.method) {
        case DEFLATED:
            super.write(b, off, len);
            break;
        case STORED:
            written += len;
            if (written - locoff > entry.size) {
                throw new ZipException("attempt to write past end of STORED entry");
            }
            out.write(b, off, len);
            break;
        default:
            throw new ZipException("invalid compression method");
    }
    crc.update(b, off, len);
}
项目:framework    文件:ZipInputStream.java   
private void readEnd(ZipEntry e) throws IOException {
    int n = inf.getRemaining();
    if (n > 0) {
        ((PushbackInputStream) in).unread(buf, len - n, n);
    }
    if ((flag & 8) == 8) {
    /* "Data Descriptor" present */
        readFully(tmpbuf, 0, EXTHDR);
        long sig = get32(tmpbuf, 0);
        if (sig != EXTSIG) { // no EXTSIG present
            e.crc = sig;
            e.csize = get32(tmpbuf, EXTSIZ - EXTCRC);
            e.size = get32(tmpbuf, EXTLEN - EXTCRC);
            ((PushbackInputStream) in).unread(tmpbuf, EXTHDR - EXTCRC - 1, EXTCRC);
        } else {
            e.crc = get32(tmpbuf, EXTCRC);
            e.csize = get32(tmpbuf, EXTSIZ);
            e.size = get32(tmpbuf, EXTLEN);
        }
    }
    if (e.size != inf.getBytesWritten()) {
        throw new ZipException("invalid entry size (expected " + e.size + " but got " + inf.getBytesWritten() + " bytes)");
    }
    if (e.csize != inf.getBytesRead()) {
        throw new ZipException("invalid entry compressed size (expected " + e.csize + " but got " + inf.getBytesRead() + " bytes)");
    }
    if (e.crc != crc.getValue()) {
        throw new ZipException("invalid entry CRC (expected 0x" + Long.toHexString(e.crc) + " but got 0x" + Long.toHexString(crc.getValue()) + ")");
    }
}
项目:r8    文件:CompatDx.java   
private static void writeZipWithClasses(List<Path> inputs, D8Output output, Path path)
    throws IOException {
  try (Closer closer = Closer.create()) {
    try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(path))) {
      // For each input archive file, add all class files within.
      for (Path input : inputs) {
        if (isArchive(input)) {
          try (ZipInputStream in = new ZipInputStream(Files.newInputStream(input))) {
            ZipEntry entry;
            while ((entry = in.getNextEntry()) != null) {
              if (isClassFile(Paths.get(entry.getName()))) {
                addEntry(entry.getName(), in, out);
              }
            }
          } catch (ZipException e) {
            throw new CompilationError(
                "Zip error while reading '" + input + "': " + e.getMessage(), e);
          }
        }
      }
      // Add dex files.
      List<Resource> dexProgramSources = output.getDexResources();
      for (int i = 0; i < dexProgramSources.size(); i++) {
        addEntry(getDexFileName(i), closer.register(dexProgramSources.get(i).getStream()), out);
      }
    }
  }
}
项目:cf-java-client-sap    文件:AbstractApplicationArchiveTest.java   
@Before
public void setup() throws ZipException, IOException {
    this.zipFile = new ZipFile(SampleProjects.springTravel());
    this.archive = newApplicationArchive(zipFile);
    this.archiveEntries = new HashMap<String, ApplicationArchive.Entry>();
    for (ApplicationArchive.Entry entry : archive.getEntries()) {
        archiveEntries.put(entry.getName(), entry);
    }
}
项目:shabdiz    文件:CompressionUtil.java   
private static void putZipEntry(final ZipOutputStream zip, final BufferedInputStream in, final ZipEntry entry) throws IOException {
    try {
        zip.putNextEntry(entry);
        IOUtils.copy(in, zip);
    }
    catch (final ZipException e) {
        LOGGER.warn("failed to put entry to zip stream", e);
    }
    finally {
        in.close();
    }
}
项目:truevfs    文件:AbstractZipFile.java   
/**
 * Reads the given {@code zip} file in order to provide random access
 * to its entries.
 *
 * @param  source the source for reading the ZIP file from.
 * @param  param the parameters for reading the ZIP file.
 * @throws ZipException if the source data is not compatible to the ZIP
 *         File Format Specification.
 * @throws EOFException on unexpected end-of-file.
 * @throws IOException on any I/O error.
 * @see    #recoverLostEntries()
 */
@CreatesObligation
protected AbstractZipFile(
        final Source source,
        final ZipFileParameters<E> param)
throws ZipException, EOFException, IOException {
    this.param = param;
    final SeekableByteChannel channel = this.channel = source.channel();
    try {
        length = channel.size();
        charset = param.getCharset();
        final @WillNotClose SeekableByteChannel
                bchannel = new SafeBufferedReadOnlyChannel(channel, length);
        if (!param.getPreambled()) checkZipFileSignature(bchannel);
        final int numEntries = findCentralDirectory(bchannel, param.getPostambled());
        mountCentralDirectory(bchannel, numEntries);
        if (preamble + postamble >= length) {
            assert 0 == numEntries;
            if (param.getPreambled()) // otherwise already checked
                checkZipFileSignature(bchannel);
        }
        assert null != channel;
        assert null != charset;
        assert null != entries;
        assert null != mapper;
        // Do NOT close bchannel - would close channel as well!
    } catch (final Throwable e1) {
        try {
            channel.close();
        } catch (final Throwable e2) {
            e1.addSuppressed(e2);
        }
        throw e1;
    }
}
项目:truevfs    文件:AbstractZipOutputStream.java   
@Override
public void init(final ZipEntry entry) throws ZipException {
    {
        final long size = encode(entry.getName()).length
                        + entry.getRawExtraFields().length
                        + encode(entry.getRawComment()).length;
        if (UShort.MAX_VALUE < size)
            throw new ZipException(entry.getName()
                    + " (the total size of "
                    + size
                    + " bytes for the name, extra fields and comment exceeds the maximum size of "
                    + UShort.MAX_VALUE + " bytes)");
    }
    if (STORED == entry.getMethod() || !this.process) {
        if (UNKNOWN == entry.getCrc())
            throw new ZipException(entry.getName()
                    + " (unknown CRC-32 value)");
        if (UNKNOWN == entry.getCompressedSize())
            throw new ZipException(entry.getName()
                    + " (unknown compressed size)");
        if (UNKNOWN == entry.getSize())
            throw new ZipException(entry.getName()
                    + " (unknown uncompressed size)");
    }
    if (UNKNOWN == entry.getPlatform())
        entry.setRawPlatform(PLATFORM_FAT);
    if (UNKNOWN == entry.getTime())
        entry.setTime(System.currentTimeMillis());
    this.entry = entry;
}
项目:HybridForAndroid    文件:ZipUtils.java   
/**
  * 解压缩一个文件
  *
  * @param zipFile 压缩文件
  * @param folderPath 解压缩的目标目录
  * @throws IOException 当解压缩过程出错时抛出
  */
 public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
     File desDir = new File(folderPath);
     if (!desDir.exists()) {
         desDir.mkdirs();
     }
     ZipFile zf = new ZipFile(zipFile);
     for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
         ZipEntry entry = ((ZipEntry)entries.nextElement());
         if (entry.isDirectory()) {

            continue;
}
         InputStream in = zf.getInputStream(entry);
         String str = folderPath + File.separator + entry.getName();
         str = new String(str.getBytes(), "utf-8");
         File desFile = new File(str);
         if (!desFile.exists()) {
             File fileParentDir = desFile.getParentFile();
             if (!fileParentDir.exists()) {
                 fileParentDir.mkdirs();
             }
             desFile.createNewFile();
         }
         OutputStream out = new FileOutputStream(desFile);
         byte buffer[] = new byte[BUFF_SIZE];
         int realLength;
         while ((realLength = in.read(buffer)) > 0) {
             out.write(buffer, 0, realLength);
         }
         in.close();
         out.close();
     }
 }
项目:tomcat7    文件:WARDirContext.java   
/**
 * Content accessor.
 * 
 * @return InputStream
 */
@Override
public InputStream streamContent()
    throws IOException {
    try {
        if (binaryContent == null) {
            InputStream is = base.getInputStream(entry);
            inputStream = is;
            return is;
        }
    } catch (ZipException e) {
        throw new IOException(e.getMessage(), e);
    }
    return super.streamContent();
}
项目:atlas    文件:CodeInjectByJavassist.java   
private static JarFile newJarFile(File jar) throws IOException {
    try {
        return new JarFile(jar);
    } catch (ZipException zex) {
        throw new ZipException("error in opening zip file " + jar);
    }
}
项目:atlas    文件:ZipUtil.java   
static CentralDirectory findCentralDirectory(RandomAccessFile raf) throws IOException,
        ZipException {
    long scanOffset = raf.length() - ENDHDR;
    if (scanOffset < 0) {
        throw new ZipException("File too short to be a zip file: " + raf.length());
    }

    long stopOffset = scanOffset - 0x10000 /* ".ZIP file comment"'s max length */;
    if (stopOffset < 0) {
        stopOffset = 0;
    }

    int endSig = Integer.reverseBytes(ENDSIG);
    while (true) {
        raf.seek(scanOffset);
        if (raf.readInt() == endSig) {
            break;
        }

        scanOffset--;
        if (scanOffset < stopOffset) {
            throw new ZipException("End Of Central Directory signature not found");
        }
    }
    // Read the End Of Central Directory. ENDHDR includes the signature
    // bytes,
    // which we've already read.

    // Pull out the information we need.
    raf.skipBytes(2); // diskNumber
    raf.skipBytes(2); // diskWithCentralDir
    raf.skipBytes(2); // numEntries
    raf.skipBytes(2); // totalNumEntries
    CentralDirectory dir = new CentralDirectory();
    dir.size = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL;
    dir.offset = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL;
    return dir;
}
项目:CorePatch    文件:DefaultDeflateCompressionDiviner.java   
/**
 * Determines the original {@link JreDeflateParameters} that were used to compress a given piece
 * of deflated delivery.
 *
 * @param compressedDataInputStreamFactory a {@link MultiViewInputStreamFactory} that can provide
 *     multiple independent {@link InputStream} instances for the compressed delivery.
 * @return the parameters that can be used to replicate the compressed delivery in the {@link
 *     DefaultDeflateCompatibilityWindow}, if any; otherwise <code>null</code>. Note that <code>
 *     null</code> is also returned in the case of <em>corrupt</em> zip delivery since, by definition,
 *     it cannot be replicated via any combination of normal deflate parameters.
 * @throws IOException if there is a problem reading the delivery, i.e. if the file contents are
 *     changed while reading
 */
public JreDeflateParameters divineDeflateParameters(
    MultiViewInputStreamFactory compressedDataInputStreamFactory) throws IOException {
  byte[] copyBuffer = new byte[32 * 1024];
  // Iterate over all relevant combinations of nowrap, strategy and level.
  for (boolean nowrap : new boolean[] {true, false}) {
    Inflater inflater = new Inflater(nowrap);
    Deflater deflater = new Deflater(0, nowrap);

    strategy_loop:
    for (int strategy : new int[] {0, 1, 2}) {
      deflater.setStrategy(strategy);
      for (int level : LEVELS_BY_STRATEGY.get(strategy)) {
        deflater.setLevel(level);
        inflater.reset();
        deflater.reset();
        try {
          if (matches(inflater, deflater, compressedDataInputStreamFactory, copyBuffer)) {
            end(inflater, deflater);
            return JreDeflateParameters.of(level, strategy, nowrap);
          }
        } catch (ZipException e) {
          // Parse error in input. The only possibilities are corruption or the wrong nowrap.
          // Skip all remaining levels and strategies.
          break strategy_loop;
        }
      }
    }
    end(inflater, deflater);
  }
  return null;
}
项目:CorePatch    文件:MinimalZipParser.java   
/**
 * Parses one local file entry and returns the offset from the first byte at which the compressed
 * data begins
 * @param in the input stream to read from, assumed to start at the first byte of the entry
 * @return as described
 * @throws IOException if unable to complete the parsing
 */
public static long parseLocalEntryAndGetCompressedDataOffset(InputStream in) throws IOException {
  // *** 4 bytes encode the LOCAL_ENTRY_SIGNATURE, verify for sanity
  // 2 bytes encode the version-needed-to-extract, ignore
  // 2 bytes encode the general-purpose flags, ignore
  // 2 bytes encode the compression method, ignore (redundant with central directory)
  // 2 bytes encode the MSDOS last modified file time, ignore
  // 2 bytes encode the MSDOS last modified file date, ignore
  // 4 bytes encode the CRC32 of the uncompressed data, ignore (redundant with central directory)
  // 4 bytes encode the compressed size, ignore (redundant with central directory)
  // 4 bytes encode the uncompressed size, ignore (redundant with central directory)
  // *** 2 bytes encode the length of the file name, needed to skip the bytes later [READ THIS]
  // *** 2 bytes encode the length of the extras, needed to skip the bytes later [READ THIS]
  // The rest is the data, which is the main attraction here.
  if (((int) read32BitUnsigned(in)) != LOCAL_ENTRY_SIGNATURE) {
    throw new ZipException("Bad local entry header");
  }
  int junkLength = 2 + 2 + 2 + 2 + 2 + 4 + 4 + 4;
  skipOrDie(in, junkLength); // Skip everything up to the length of the file name
  final int fileNameLength = read16BitUnsigned(in);
  final int extrasLength = read16BitUnsigned(in);

  // The file name is already known and will match the central directory, so no need to read it.
  // The extra field length can be different here versus in the central directory and is used for
  // things like zipaligning APKs. This single value is the critical part as it dictates where the
  // actual DATA for the entry begins.
  return 4 + junkLength + 2 + 2 + fileNameLength + extrasLength;
}
项目:letv    文件:ZipUtils.java   
public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
    File desDir = new File(folderPath);
    if (!desDir.exists()) {
        desDir.mkdirs();
    }
    ZipFile zf = new ZipFile(zipFile);
    Enumeration<?> entries = zf.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        InputStream in = zf.getInputStream(entry);
        File desFile = new File(new String(new StringBuilder(String.valueOf(folderPath)).append(File.separator).append(entry.getName()).toString().getBytes("8859_1"), "GB2312"));
        if (!desFile.exists()) {
            File fileParentDir = desFile.getParentFile();
            if (!fileParentDir.exists()) {
                fileParentDir.mkdirs();
            }
            desFile.createNewFile();
        }
        OutputStream out = new FileOutputStream(desFile);
        byte[] buffer = new byte[1048576];
        while (true) {
            int realLength = in.read(buffer);
            if (realLength <= 0) {
                break;
            }
            out.write(buffer, 0, realLength);
        }
        in.close();
        out.close();
    }
}