Java Code Examples for java.util.zip.ZipException

The following examples show how to use java.util.zip.ZipException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: grpc-nebula-java   Author: grpc-nebula   File: GzipInflatingBuffer.java    License: Apache License 2.0 6 votes vote down vote up
private boolean processTrailer() throws ZipException {
  if (inflater != null
      && gzipMetadataReader.readableBytes() <= GZIP_HEADER_MIN_SIZE + GZIP_TRAILER_SIZE) {
    // We don't have enough bytes to begin inflating a concatenated gzip stream, drop context
    inflater.end();
    inflater = null;
  }
  if (gzipMetadataReader.readableBytes() < GZIP_TRAILER_SIZE) {
    return false;
  }
  if (crc.getValue() != gzipMetadataReader.readUnsignedInt()
      || expectedGzipTrailerIsize != gzipMetadataReader.readUnsignedInt()) {
    throw new ZipException("Corrupt GZIP trailer");
  }
  crc.reset();
  state = State.HEADER;
  return true;
}
 
Example #2
Source Project: NotEnoughItems   Author: TheCBProject   File: NEIServerUtils.java    License: MIT License 6 votes vote down vote up
public static NBTTagCompound readNBT(File file) throws IOException {
    if (!file.exists()) {
        return null;
    }
    FileInputStream in = new FileInputStream(file);
    NBTTagCompound tag;
    try {
        tag = CompressedStreamTools.readCompressed(in);
    } catch (ZipException e) {
        if (e.getMessage().equals("Not in GZIP format")) {
            tag = CompressedStreamTools.read(file);
        } else {
            throw e;
        }
    }
    in.close();
    return tag;
}
 
Example #3
Source Project: dragonwell8_jdk   Author: alibaba   File: ZipFileSystem.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source Project: RDFS   Author: iVCE   File: JarBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
  if (verbose) {
    System.err.println("JarBuilder.addNamedStream " + name);
  }
  try {
    dst.putNextEntry(new JarEntry(name));
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
      dst.write(buffer, 0, bytesRead);
    }
  } catch (ZipException ze) {
    if (ze.getMessage().indexOf("duplicate entry") >= 0) {
      if (verbose) {
        System.err.println(ze + " Skip duplicate entry " + name);
      }
    } else {
      throw ze;
    }
  } finally {
    in.close();
    dst.flush();
    dst.closeEntry();
  }
}
 
Example #5
Source Project: jdk8u_jdk   Author: JetBrains   File: ZipFileSystem.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #6
Source Project: jdk8u-jdk   Author: frohoff   File: ZipFileSystem.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source Project: TencentKona-8   Author: Tencent   File: ZipFileSystem.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #8
Source Project: grpc-java   Author: grpc   File: GzipInflatingBuffer.java    License: Apache License 2.0 6 votes vote down vote up
private boolean processTrailer() throws ZipException {
  if (inflater != null
      && gzipMetadataReader.readableBytes() <= GZIP_HEADER_MIN_SIZE + GZIP_TRAILER_SIZE) {
    // We don't have enough bytes to begin inflating a concatenated gzip stream, drop context
    inflater.end();
    inflater = null;
  }
  if (gzipMetadataReader.readableBytes() < GZIP_TRAILER_SIZE) {
    return false;
  }
  if (crc.getValue() != gzipMetadataReader.readUnsignedInt()
      || expectedGzipTrailerIsize != gzipMetadataReader.readUnsignedInt()) {
    throw new ZipException("Corrupt GZIP trailer");
  }
  crc.reset();
  state = State.HEADER;
  return true;
}
 
Example #9
Source Project: hadoop   Author: naver   File: JarBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
  if (verbose) {
    System.err.println("JarBuilder.addNamedStream " + name);
  }
  try {
    dst.putNextEntry(new JarEntry(name));
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
      dst.write(buffer, 0, bytesRead);
    }
  } catch (ZipException ze) {
    if (ze.getMessage().indexOf("duplicate entry") >= 0) {
      if (verbose) {
        System.err.println(ze + " Skip duplicate entry " + name);
      }
    } else {
      throw ze;
    }
  } finally {
    in.close();
    dst.flush();
    dst.closeEntry();
  }
}
 
Example #10
Source Project: Concurnas   Author: Concurnas   File: BootstrapJarLoader.java    License: MIT License 6 votes vote down vote up
private void loadJarsToLocations() throws ZipException, IOException{
	for(File zfa : this.jdkjars){
		ZipFile zf = new ZipFile(zfa);
		Enumeration<?> entries = zf.entries();
		while(entries.hasMoreElements()){
			ZipEntry ze = (ZipEntry)entries.nextElement();
			if(!ze.isDirectory()){
				String name = ze.getName();
				if(name.endsWith(".class")){
					name = name.substring(0, name.length()-6);
					
					nameToLocation.put(name, new FileAndZipEntry(zf, ze));
				}
			}
		}
	}
}
 
Example #11
Source Project: monsoon   Author: groupon   File: GzipDecodingBufferSupplier.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean read_trailer_() throws IOException {
    final int crc_value = (int)crc_.getValue();
    final int declared_crc = read_int_();
    LOG.log(Level.FINE, "crc = {0}, expecting {1}", new Object[]{crc_value, declared_crc});
    if (declared_crc != crc_value)
        throw new ZipException("CRC mismatch");

    final int declared_fsize = read_int_();
    LOG.log(Level.FINE, "fsize (modulo int) = {0}, expecting {1}", new Object[]{(int)(inflater_.getBytesWritten() & 0xffffffff), declared_fsize});
    if ((int)(inflater_.getBytesWritten() & 0xffffffff) != declared_fsize)
        throw new ZipException("File size check mismatch");

    if (raw_.atEof()) return true;  // End-of-stream.
    // Not at end of stream, assume gzip concatenation.
    read_header_();
    return false;
}
 
Example #12
Source Project: capsule-maven-plugin   Author: chrisdchristo   File: Mojo.java    License: MIT License 6 votes vote down vote up
String addDirectoryToJar(final JarOutputStream jar, final String outputDirectory) throws IOException {

		// format the output directory
		String formattedOutputDirectory = "";
		if (outputDirectory != null && !outputDirectory.isEmpty()) {
			if (!outputDirectory.endsWith("/")) {
				formattedOutputDirectory = outputDirectory + File.separatorChar;
			} else {
				formattedOutputDirectory = outputDirectory;
			}
		}

		if (!formattedOutputDirectory.isEmpty()) {
			try {
				jar.putNextEntry(new ZipEntry(formattedOutputDirectory));
				jar.closeEntry();
			} catch (final ZipException ignore) {} // ignore duplicate entries and other errors
		}
		return formattedOutputDirectory;
	}
 
Example #13
Source Project: jdk8u60   Author: chenghanpeng   File: ZipFileSystem.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #14
Source Project: hadoop-gpu   Author: koichi626   File: JarBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
  if (verbose) {
    System.err.println("JarBuilder.addNamedStream " + name);
  }
  try {
    dst.putNextEntry(new JarEntry(name));
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
      dst.write(buffer, 0, bytesRead);
    }
  } catch (ZipException ze) {
    if (ze.getMessage().indexOf("duplicate entry") >= 0) {
      if (verbose) {
        System.err.println(ze + " Skip duplicate entry " + name);
      }
    } else {
      throw ze;
    }
  } finally {
    in.close();
    dst.flush();
    dst.closeEntry();
  }
}
 
Example #15
Source Project: bazel   Author: bazelbuild   File: EndOfCentralDirectoryRecord.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates the raw byte data of the end of central directory record for the specified
 * {@link ZipFileData}.
 * @throws ZipException if the file comment is too long
 */
static byte[] create(ZipFileData file, boolean allowZip64) throws ZipException {
  byte[] comment = file.getBytes(file.getComment());

  byte[] buf = new byte[FIXED_DATA_SIZE + comment.length];

  // Allow writing of Zip file without Zip64 extensions for large archives as a special case
  // since many reading implementations can handle this.
  short numEntries = (short) (file.getNumEntries() > 0xffff && allowZip64
      ? -1 : file.getNumEntries());
  int cdSize = (int) (file.getCentralDirectorySize() > 0xffffffffL && allowZip64
      ? -1 : file.getCentralDirectorySize());
  int cdOffset = (int) (file.getCentralDirectoryOffset() > 0xffffffffL && allowZip64
      ? -1 : file.getCentralDirectoryOffset());
  ZipUtil.intToLittleEndian(buf, SIGNATURE_OFFSET, SIGNATURE);
  ZipUtil.shortToLittleEndian(buf, DISK_NUMBER_OFFSET, (short) 0);
  ZipUtil.shortToLittleEndian(buf, CD_DISK_OFFSET, (short) 0);
  ZipUtil.shortToLittleEndian(buf, DISK_ENTRIES_OFFSET, numEntries);
  ZipUtil.shortToLittleEndian(buf, TOTAL_ENTRIES_OFFSET, numEntries);
  ZipUtil.intToLittleEndian(buf, CD_SIZE_OFFSET, cdSize);
  ZipUtil.intToLittleEndian(buf, CD_OFFSET_OFFSET, cdOffset);
  ZipUtil.shortToLittleEndian(buf, COMMENT_LENGTH_OFFSET, (short) comment.length);
  System.arraycopy(comment, 0, buf, FIXED_DATA_SIZE, comment.length);

  return buf;
}
 
Example #16
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: ZipFileSystem.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #17
Source Project: jdk8u-jdk   Author: frohoff   File: ZipFileSystem.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #18
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: ZipFileIndex.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #19
Source Project: big-c   Author: yncxcw   File: JarBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
  if (verbose) {
    System.err.println("JarBuilder.addNamedStream " + name);
  }
  try {
    dst.putNextEntry(new JarEntry(name));
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
      dst.write(buffer, 0, bytesRead);
    }
  } catch (ZipException ze) {
    if (ze.getMessage().indexOf("duplicate entry") >= 0) {
      if (verbose) {
        System.err.println(ze + " Skip duplicate entry " + name);
      }
    } else {
      throw ze;
    }
  } finally {
    in.close();
    dst.flush();
    dst.closeEntry();
  }
}
 
Example #20
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: ZipFileIndex.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #21
Source Project: bazel   Author: bazelbuild   File: CentralDirectoryFileHeader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates the raw byte data of the central directory file header for the ZipEntry. Uses the
 * specified {@link ZipFileData} to encode the file name and comment.
 * @throws ZipException 
 */
static byte[] create(ZipFileEntry entry, ZipFileData file, boolean allowZip64)
    throws ZipException {
  if (allowZip64) {
    addZip64Extra(entry);
  } else {
    entry.getExtra().remove((short) 0x0001);
  }
  byte[] name = file.getBytes(entry.getName());
  byte[] extra = entry.getExtra().getBytes();
  byte[] comment = entry.getComment() != null
      ? file.getBytes(entry.getComment()) : new byte[]{};

  byte[] buf = new byte[FIXED_DATA_SIZE + name.length + extra.length + comment.length];

  fillFixedSizeData(buf, entry, name.length, extra.length, comment.length, allowZip64);
  System.arraycopy(name, 0, buf, FIXED_DATA_SIZE, name.length);
  System.arraycopy(extra, 0, buf, FIXED_DATA_SIZE + name.length, extra.length);
  System.arraycopy(comment, 0, buf, FIXED_DATA_SIZE + name.length + extra.length,
      comment.length);

  return buf;
}
 
Example #22
Source Project: bazel   Author: bazelbuild   File: ZipWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void testPrefixFileAfterZip() throws IOException {
  try (ZipWriter writer = new ZipWriter(new FileOutputStream(test), UTF_8)) {
    byte[] content = "content".getBytes(UTF_8);
    crc.update(content);
    ZipFileEntry entry = new ZipFileEntry("foo");
    entry.setSize(content.length);
    entry.setCompressedSize(content.length);
    entry.setCrc(crc.getValue());
    entry.setTime(cal.getTimeInMillis());

    writer.putNextEntry(entry);
    thrown.expect(ZipException.class);
    thrown.expectMessage("Cannot add a prefix file after the zip contents have been started.");
    writer.startPrefixFile();
  }
}
 
Example #23
Source Project: Box   Author: lulululbj   File: Path.java    License: Apache License 2.0 5 votes vote down vote up
static ClassPathElement getClassPathElement(File file)
        throws ZipException, IOException {
    if (file.isDirectory()) {
        return new FolderPathElement(file);
    } else if (file.isFile()) {
        return new ArchivePathElement(new ZipFile(file));
    } else if (file.exists()) {
        throw new IOException("\"" + file.getPath() +
                "\" is not a directory neither a zip file");
    } else {
        throw new FileNotFoundException("File \"" + file.getPath() + "\" not found");
    }
}
 
Example #24
Source Project: furnace   Author: forge   File: BootstrapClassLoader.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private List<URL> handleZipFile(File file) throws IOException
{
   File tempDir = OperatingSystemUtils.createTempDir();
   List<URL> result = new ArrayList<>();
   try
   {
      ZipFile zip = new ZipFile(file);
      Enumeration<? extends ZipEntry> entries = zip.entries();
      while (entries.hasMoreElements())
      {
         ZipEntry entry = entries.nextElement();
         String name = entry.getName();
         if (name.matches(path + "/.*\\.jar"))
         {
            log.log(Level.FINE, String.format("ZipEntry detected: %s len %d added %TD",
                     file.getAbsolutePath() + "/" + entry.getName(), entry.getSize(),
                     new Date(entry.getTime())));

            result.add(copy(tempDir, entry.getName(),
                     JarLocator.class.getClassLoader().getResource(name).openStream()
                     ).toURL());
         }
      }
      zip.close();
   }
   catch (ZipException e)
   {
      throw new RuntimeException("Error handling file " + file, e);
   }
   return result;
}
 
Example #25
Source Project: wildfly-core   Author: wildfly   File: PathUtil.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test if the target path is an archive.
 * @param path path to the file.
 * @return true if the path points to a zip file - false otherwise.
 * @throws IOException
 */
public static final boolean isArchive(Path path) throws IOException {
    if (Files.exists(path) && Files.isRegularFile(path)) {
        try (ZipFile zip = new ZipFile(path.toFile())){
            return true;
        } catch (ZipException e) {
            return false;
        }
    }
    return false;
}
 
Example #26
Source Project: appcan-android   Author: AppCanOpenSource   File: CnZipInputStream.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private void readEnd(ZipEntry e) throws IOException {
    int n = this.inf.getRemaining();
    if (n > 0) {
        ((PushbackInputStream) this.in).unread(this.buf, this.len - n, n);
    }
    if ((e.flag & 0x8) == 8) {
        readFully(this.tmpbuf, 0, 16);
        long sig = get32(this.tmpbuf, 0);
        if (sig != 134695760L) {
            e.crc = sig;
            e.csize = get32(this.tmpbuf, 4);
            e.size = get32(this.tmpbuf, 8);
            ((PushbackInputStream) this.in).unread(this.tmpbuf, 11, 4);
        } else {
            e.crc = get32(this.tmpbuf, 4);
            e.csize = get32(this.tmpbuf, 8);
            e.size = get32(this.tmpbuf, 12);
        }
    }
    if (e.size != this.inf.getTotalOut()) {
        throw new ZipException("invalid entry size (expected " + e.size
                + " but got " + this.inf.getTotalOut() + " bytes)");
    }
    if (e.csize != this.inf.getTotalIn()) {
        throw new ZipException("invalid entry compressed size (expected "
                + e.csize + " but got " + this.inf.getTotalIn() + " bytes)");
    }
    if (e.crc != this.crc.getValue())
        throw new ZipException("invalid entry CRC (expected 0x"
                + Long.toHexString(e.crc) + " but got 0x"
                + Long.toHexString(this.crc.getValue()) + ")");
}
 
Example #27
Source Project: consulo   Author: consulo   File: JBZipEntry.java    License: Apache License 2.0 5 votes vote down vote up
private InputStream getInputStream() throws IOException {
  long start = calcDataOffset();

  BoundedInputStream bis = new BoundedInputStream(start, getCompressedSize());
  switch (getMethod()) {
    case ZipEntry.STORED:
      return bis;
    case ZipEntry.DEFLATED:
      bis.addDummy();
      return new InflaterInputStream(bis, new Inflater(true));
    default:
      throw new ZipException("Found unsupported compression method " + getMethod());
  }
}
 
Example #28
Source Project: bonita-ui-designer   Author: bonitasoft   File: Unzipper.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Path unzipInTempDir(InputStream is, String tempDirPrefix) throws IOException {
    Path tempDirectory = Files.createTempDirectory(temporaryZipPath, tempDirPrefix);
    Path zipFile = writeInDir(is, tempDirectory);
    try {
        ZipUtil.unpack(zipFile.toFile(), tempDirectory.toFile());
    } catch (org.zeroturnaround.zip.ZipException e) {
        throw new ZipException(e.getMessage());
    } finally {
        FileUtils.deleteQuietly(zipFile.toFile());
    }
    return tempDirectory;
}
 
Example #29
Source Project: javaide   Author: tranleduy2000   File: Path.java    License: GNU General Public License v3.0 5 votes vote down vote up
static ClassPathElement getClassPathElement(File file)
        throws ZipException, IOException {
    if (file.isDirectory()) {
        return new FolderPathElement(file);
    } else if (file.isFile()) {
        return new ArchivePathElement(new ZipFile(file));
    } else if (file.exists()) {
        throw new IOException("\"" + file.getPath() +
                "\" is not a directory neither a zip file");
    } else {
        throw new FileNotFoundException("File \"" + file.getPath() + "\" not found");
    }
}
 
Example #30
Source Project: android-tv-launcher   Author: sunglasscat   File: ZipUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 解压文件名包含传入文字的文件
 *
 * @param zipFile 压缩文件
 * @param folderPath 目标文件夹
 * @param nameContains 传入的文件匹配名
 * @throws ZipException 压缩格式有误时抛出
 * @throws IOException IO错误时抛出
 */
public static ArrayList<File> upZipSelectedFile(File zipFile, String folderPath,
        String nameContains) throws ZipException, IOException {
    ArrayList<File> fileList = new ArrayList<File>();
 
    File desDir = new File(folderPath);
    if (!desDir.exists()) {
        desDir.mkdir();
    }
 
    ZipFile zf = new ZipFile(zipFile);
    for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
        ZipEntry entry = ((ZipEntry)entries.nextElement());
        if (entry.getName().contains(nameContains)) {
            InputStream in = zf.getInputStream(entry);
            String str = folderPath + File.separator + entry.getName();
            str = new String(str.getBytes("8859_1"), "GB2312");
            // str.getBytes("GB2312"),"8859_1" 输出
            // str.getBytes("8859_1"),"GB2312" 输入
            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();
            fileList.add(desFile);
        }
    }
    return fileList;
}