コード例 #1
1
  public static void unzipIntoDirectory(InputStream inputStream, File directory) {
    if (directory.isFile()) return;
    directory.mkdirs();

    try {
      inputStream = new BufferedInputStream(inputStream);
      inputStream = new ZipInputStream(inputStream);

      for (ZipEntry entry = null;
          (entry = ((ZipInputStream) inputStream).getNextEntry()) != null; ) {
        StringBuilder pathBuilder =
            new StringBuilder(directory.getPath()).append('/').append(entry.getName());
        File file = new File(pathBuilder.toString());

        if (entry.isDirectory()) {
          file.mkdirs();
          continue;
        }

        StreamUtil.write(pathBuilder, inputStream, false);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      StreamUtil.closeQuietly(inputStream);
    }
  }
コード例 #2
0
 /**
  * Helper for unzipping downloaded zips
  *
  * @param environment
  * @throws IOException
  */
 private void unzip(Environment environment, ZipFile zipFile, File targetFile, String targetPath)
     throws IOException {
   String baseDirSuffix = null;
   try {
     Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
     if (!zipEntries.hasMoreElements()) {
       logger.error("the zip archive has no entries");
     }
     ZipEntry firstEntry = zipEntries.nextElement();
     if (firstEntry.isDirectory()) {
       baseDirSuffix = firstEntry.getName();
     } else {
       zipEntries = zipFile.entries();
     }
     while (zipEntries.hasMoreElements()) {
       ZipEntry zipEntry = zipEntries.nextElement();
       if (zipEntry.isDirectory()) {
         continue;
       }
       String zipEntryName = zipEntry.getName();
       zipEntryName = zipEntryName.replace('\\', '/');
       if (baseDirSuffix != null && zipEntryName.startsWith(baseDirSuffix)) {
         zipEntryName = zipEntryName.substring(baseDirSuffix.length());
       }
       File target = new File(targetFile, zipEntryName);
       FileSystemUtils.mkdirs(target.getParentFile());
       Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target));
     }
   } catch (IOException e) {
     logger.error(
         "failed to extract zip ["
             + zipFile.getName()
             + "]: "
             + ExceptionsHelper.detailedMessage(e));
     return;
   } finally {
     try {
       zipFile.close();
     } catch (IOException e) {
       // ignore
     }
   }
   File binFile = new File(targetFile, "bin");
   if (binFile.exists() && binFile.isDirectory()) {
     File toLocation = new File(new File(environment.homeFile(), "bin"), targetPath);
     logger.info("found bin, moving to " + toLocation.getAbsolutePath());
     FileSystemUtils.deleteRecursively(toLocation);
     binFile.renameTo(toLocation);
   }
   if (!new File(targetFile, "_site").exists()) {
     if (!FileSystemUtils.hasExtensions(targetFile, ".class", ".jar")) {
       logger.info("identified as a _site plugin, moving to _site structure ...");
       File site = new File(targetFile, "_site");
       File tmpLocation = new File(environment.pluginsFile(), targetPath + ".tmp");
       targetFile.renameTo(tmpLocation);
       FileSystemUtils.mkdirs(targetFile);
       tmpLocation.renameTo(site);
     }
   }
 }
コード例 #3
0
 public static void unzip(File zipFile, File targetDirectory) throws IOException {
   ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
   try {
     ZipEntry ze;
     int count;
     byte[] buffer = new byte[8192];
     while ((ze = zis.getNextEntry()) != null) {
       File file = new File(targetDirectory, ze.getName());
       File dir = ze.isDirectory() ? file : file.getParentFile();
       if (!dir.isDirectory() && !dir.mkdirs())
         throw new FileNotFoundException("Failed to ensure directory: " + dir.getAbsolutePath());
       if (ze.isDirectory()) continue;
       FileOutputStream fout = new FileOutputStream(file);
       try {
         while ((count = zis.read(buffer)) != -1) fout.write(buffer, 0, count);
       } finally {
         fout.close();
       }
       /* if time should be restored as well
       long time = ze.getTime();
       if (time > 0)
           file.setLastModified(time);
       */
     }
   } finally {
     zis.close();
   }
 }
コード例 #4
0
  public String unzip(String destinationName, String zipFileName) {
    String rootFolder = null;

    try {
      byte[] buf = new byte[1024];
      ZipInputStream zipinputstream;
      ZipEntry zipentry;
      zipinputstream = new ZipInputStream(new FileInputStream(zipFileName));
      boolean isFirstRun = true;

      zipentry = zipinputstream.getNextEntry();
      while (zipentry != null) {
        // for each entry to be extracted
        String entryName = destinationName + zipentry.getName();
        entryName = entryName.replace('/', File.separatorChar);
        entryName = entryName.replace('\\', File.separatorChar);
        System.out.println("entryname " + entryName);
        int n;
        File newFile = new File(entryName);
        if (isFirstRun && !zipentry.isDirectory()) {
          fail("zip file must contain folder at root");
        } else {
          isFirstRun = false;
          rootFolder = zipentry.getName();
        }
        if (zipentry.isDirectory()) {
          if (!newFile.mkdirs()) {
            break;
          }
          zipentry = zipinputstream.getNextEntry();
          continue;
        }

        FileOutputStream fileoutputstream = new FileOutputStream(entryName);

        while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
          fileoutputstream.write(buf, 0, n);
        }

        fileoutputstream.flush();
        fileoutputstream.close();
        zipinputstream.closeEntry();
        zipentry = zipinputstream.getNextEntry();
      } // while

      zipinputstream.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return rootFolder;
  }
コード例 #5
0
 protected static boolean isNoteFile(ZipEntry entry) {
   if (entry.isDirectory()) return false;
   String name = entry.getName();
   if (name.contains("/") || name.contains("\\")) return false;
   if (name.toLowerCase().endsWith("." + FORMAT_EXPORT)) return true;
   return false;
 }
コード例 #6
0
  /**
   * Constructor.
   *
   * @param codeBaseLocator the codebase locator for this codebase
   * @param file the File containing the zip file (may be a temp file if the codebase was copied
   *     from a nested zipfile in another codebase)
   */
  public ZipInputStreamCodeBase(ICodeBaseLocator codeBaseLocator, File file) throws IOException {
    super(codeBaseLocator);

    this.file = file;
    setLastModifiedTime(file.lastModified());
    ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
    try {
      ZipEntry ze;

      if (DEBUG) {
        System.out.println("Reading zip input stream " + file);
      }

      while ((ze = zis.getNextEntry()) != null) {
        String name = ze.getName();
        if (!ze.isDirectory()
            && (name.equals("META-INF/MANIFEST.MF")
                || name.endsWith(".class")
                || Archive.isArchiveFileName(name))) {
          entries.add(name);
          if (name.equals("META-INF/MANIFEST.MF")) {
            map.put(name, build(zis, ze));
          }
        }
        zis.closeEntry();
      }
    } finally {
      zis.close();
    }
    if (DEBUG) {
      System.out.println("Done with zip input stream " + file);
    }
  }
コード例 #7
0
  public void unzip(File from, String to) throws FITTESTException {
    try {
      FileInputStream fis = new FileInputStream(from);
      ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis, BUFFER));
      ZipEntry entry = zis.getNextEntry();
      while (entry != null) {
        int count;
        byte data[] = new byte[BUFFER];

        File outFile = null;
        if (entry.isDirectory()) {
          outFile = new File(to, entry.getName());
          outFile.mkdirs();
        } else {
          outFile = new File(to, entry.getName());

          FileOutputStream fos = new FileOutputStream(outFile);
          BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
          while ((count = zis.read(data, 0, BUFFER)) != -1) {
            bos.write(data, 0, count);
          }
          bos.flush();
          bos.close();
        }
        zis.closeEntry();

        entry = zis.getNextEntry();
      }
      zis.close();
    } catch (Exception e) {
      throw new FITTESTException(e.getMessage());
    }
  }
コード例 #8
0
ファイル: Zips.java プロジェクト: jinahya/jinahya-se
  protected static File file(final File root, final ZipEntry entry) throws IOException {

    if (root == null) {
      throw new NullPointerException("root");
    }

    if (!root.isDirectory()) {
      throw new IllegalArgumentException("root is not an existing directory");
    }

    if (entry == null) {
      throw new NullPointerException("entry");
    }

    final File file = new File(root, entry.getName());

    File parent = file;
    if (!entry.isDirectory()) {
      final String name = entry.getName();
      final int index = name.lastIndexOf('/');
      if (index != -1) {
        parent = new File(root, name.substring(0, index));
      }
    }
    if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
      throw new IOException("failed to create a directory: " + parent.getPath());
    }

    return file;
  }
コード例 #9
0
ファイル: MyZip.java プロジェクト: zengyun2020/Git_code
  /**
   * Unzip given file into given folder.
   *
   * @param fileZip : zip file to unzip.
   * @param dirOut : folder where to put the unzipped files.
   */
  public static void unzip(File fileZip, File dirOut) {
    try {
      byte[] buf = new byte[10 * 1024];
      if (!fileZip.canRead()) throw new IllegalArgumentException(fileZip.getAbsolutePath());
      if (!dirOut.isDirectory()) dirOut.mkdirs();
      if (!dirOut.isDirectory()) throw new IllegalArgumentException(dirOut.getAbsolutePath());

      FileInputStream fin = new FileInputStream(fileZip);
      ZipInputStream zin = new ZipInputStream(fin);
      ZipEntry ze = null;
      while ((ze = zin.getNextEntry()) != null) {
        File fileZe = new File(dirOut, ze.getName());
        Log.i("Zip", fileZe.getAbsolutePath());
        if (ze.isDirectory()) continue;
        assureParentExists(fileZe);
        BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(fileZe));
        while (true) {
          int read = zin.read(buf);
          if (-1 == read) break; // End of file.
          fout.write(buf, 0, read);
        }
        zin.closeEntry();
        fout.close();
      }
      zin.close();
    } catch (Exception e) {
      Log.e("MyZip", "unzip", e);
    }
  }
コード例 #10
0
 public static boolean isJarDirectory(String path) {
   if (isJarFile()) {
     try {
       JarFile jar = new JarFile(getJarFile());
       ZipEntry entry = jar.getEntry(path);
       return entry != null && entry.isDirectory();
     } catch (Exception e) {
       e.printStackTrace();
     }
   } else {
     try {
       URL url = FileUtilities.class.getResource("/" + path);
       if (url != null) {
         URI uri = url.toURI();
         File classpath = new File(uri);
         return classpath.isDirectory();
       } else {
         return false;
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return false;
 }
コード例 #11
0
  private void loadAll() {
    mFiles = new LinkedHashSet<String>();
    mDirs = new LinkedHashMap<String, AbstractDirectory>();

    int prefixLen = getPath().length();
    Enumeration<? extends ZipEntry> entries = getZipFile().entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry = entries.nextElement();
      String name = entry.getName();

      if (name.equals(getPath()) || !name.startsWith(getPath())) {
        continue;
      }

      String subname = name.substring(prefixLen);

      int pos = subname.indexOf(separator);
      if (pos == -1) {
        if (!entry.isDirectory()) {
          mFiles.add(subname);
          continue;
        }
      } else {
        subname = subname.substring(0, pos);
      }

      if (!mDirs.containsKey(subname)) {
        AbstractDirectory dir = new ZipRODirectory(getZipFile(), getPath() + subname + separator);
        mDirs.put(subname, dir);
      }
    }
  }
コード例 #12
0
  public ZipRepository(final InputStream in, final MimeRegistry mimeRegistry) throws IOException {
    this(mimeRegistry);

    final ZipInputStream zipIn = new ZipInputStream(in);
    try {
      ZipEntry nextEntry = zipIn.getNextEntry();
      while (nextEntry != null) {
        final String[] buildName = RepositoryUtilities.splitPath(nextEntry.getName(), "/");
        if (nextEntry.isDirectory()) {
          root.updateDirectoryEntry(buildName, 0, nextEntry);
        } else {
          final ByteArrayOutputStream bos = new ByteArrayOutputStream();
          final Deflater def = new Deflater(nextEntry.getMethod());
          try {
            final DeflaterOutputStream dos = new DeflaterOutputStream(bos, def);
            try {
              IOUtils.getInstance().copyStreams(zipIn, dos);
              dos.flush();
            } finally {
              dos.close();
            }
          } finally {
            def.end();
          }

          root.updateEntry(buildName, 0, nextEntry, bos.toByteArray());
        }

        zipIn.closeEntry();
        nextEntry = zipIn.getNextEntry();
      }
    } finally {
      zipIn.close();
    }
  }
コード例 #13
0
ファイル: SourceFinder.java プロジェクト: krosenvold/findbugs
    InMemorySourceRepository(@WillClose ZipInputStream in) throws IOException {
      try {
        while (true) {

          ZipEntry e = in.getNextEntry();
          if (e == null) break;
          if (!e.isDirectory()) {
            String name = e.getName();
            long size = e.getSize();

            if (size > Integer.MAX_VALUE)
              throw new IOException(name + " is too big at " + size + " bytes");
            ByteArrayOutputStream out;
            if (size <= 0) out = new ByteArrayOutputStream();
            else out = new ByteArrayOutputStream((int) size);
            GZIPOutputStream gOut = new GZIPOutputStream(out);
            IO.copy(in, gOut);
            gOut.close();
            byte data[] = out.toByteArray();
            contents.put(name, data);
            lastModified.put(name, e.getTime());
          }
          in.closeEntry();
        }
      } finally {
        Util.closeSilently(in);
      }
    }
コード例 #14
0
ファイル: ZipUtility.java プロジェクト: ranvirp/Bw
  public static final void unzip(File zip, File extractTo) throws IOException {
    ZipFile archive = new ZipFile(zip);
    Enumeration e = archive.entries();
    while (e.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) e.nextElement();
      File file = new File(extractTo, entry.getName());
      if (entry.isDirectory() && !file.exists()) {
        file.mkdirs();
      } else {
        if (!file.getParentFile().exists()) {
          file.getParentFile().mkdirs();
        }

        InputStream in = archive.getInputStream(entry);
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));

        byte[] buffer = new byte[8192];
        int read;

        while (-1 != (read = in.read(buffer))) {
          out.write(buffer, 0, read);
        }

        in.close();
        out.close();
      }
    }
  }
コード例 #15
0
ファイル: ZipUtil.java プロジェクト: llyloveyh/CDOJ
 /**
  * Unzip the zip file and put all the files in the zip file to the path.
  *
  * <p><strong>WARN:</strong> If the file list can not pass the checker's validation, delete all
  * the contents in the {@code path}, and the {@code path} itself.
  *
  * @param zipFile zipFile object
  * @param path target path
  * @param checker checker to validate ZIP files.
  * @throws AppException if exception occurred, convert them into {@code AppException} object.
  */
 public static void unzipFile(ZipFile zipFile, String path, Checker<File> checker)
     throws AppException {
   try {
     Enumeration<?> enumeration = zipFile.entries();
     while (enumeration.hasMoreElements()) {
       ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
       if (zipEntry.isDirectory()) {
         if (!new File(path + "/" + zipEntry.getName()).mkdirs()) throw new Exception();
         continue;
       }
       File file = new File(path + "/" + zipEntry.getName());
       File parent = file.getParentFile();
       if (parent != null && !parent.exists()) {
         if (!parent.mkdirs()) throw new AppException();
       }
       FileUtil.saveToFile(zipFile.getInputStream(zipEntry), new FileOutputStream(file));
     }
     zipFile.close();
     File targetFile = new File(path);
     try {
       checker.check(targetFile);
     } catch (AppException e) {
       FileUtil.clearDirectory(targetFile.getAbsolutePath());
       throw e;
     }
   } catch (AppException e) {
     throw e;
   } catch (Exception e) {
     e.printStackTrace();
     throw new AppException("Unzip zip file error.");
   }
 }
コード例 #16
0
ファイル: ResourceLoader.java プロジェクト: kienle/EpubReader
  public void load() throws IOException {
    ZipInputStream in = null;

    try {
      in = new ZipInputStream(new FileInputStream(this.fileName));

      for (ZipEntry zipEntry = in.getNextEntry(); zipEntry != null; zipEntry = in.getNextEntry()) {
        if (zipEntry.isDirectory()) {
          continue;
        }

        String href = zipEntry.getName();
        List<ResourceCallback> filteredCallbacks = findCallbacksFor(href);

        if (!filteredCallbacks.isEmpty()) {
          for (ResourceCallback callback : filteredCallbacks) {
            callback.onLoadResource(href, in);
          }
        }
      }
    } finally {
      if (in != null) {
        in.close();
      }

      this.callbacks.clear();
    }
  }
コード例 #17
0
ファイル: UnzipUtil.java プロジェクト: billcode/bcdeployer
  public static final boolean unzip(File file, File target) throws MojoExecutionException {
    Enumeration entries;
    ZipFile zipFile;

    display(" --- Extracting ---");

    try {

      zipFile = new ZipFile(file);

      entries = zipFile.entries();

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

        if (entry.isDirectory()) {
          display("       + " + entry.getName());
          File newFolder = new File(target + "/" + entry.getName());
          newFolder.mkdir();
          continue;
        }

        display("         " + entry.getName());
        copyInputStream(
            zipFile.getInputStream(entry),
            new BufferedOutputStream(new FileOutputStream(target + "/" + entry.getName())));
      }

      zipFile.close();
      return true;

    } catch (IOException ioe) {
      throw new MojoExecutionException("Unzip Error", ioe);
    }
  }
コード例 #18
0
 private static void unZipFile(InputStream source, FileObject projectRoot) throws IOException {
   try {
     ZipInputStream str = new ZipInputStream(source);
     ZipEntry entry;
     while ((entry = str.getNextEntry()) != null) {
       if (entry.isDirectory()) {
         FileUtil.createFolder(projectRoot, entry.getName());
       } else {
         FileObject fo = FileUtil.createData(projectRoot, entry.getName());
         FileLock lock = fo.lock();
         try {
           OutputStream out = fo.getOutputStream(lock);
           try {
             FileUtil.copy(str, out);
           } finally {
             out.close();
           }
         } finally {
           lock.releaseLock();
         }
       }
     }
   } finally {
     source.close();
   }
 }
コード例 #19
0
  private List<String> getClasses() throws IOException {
    if (zipClasses.size() != 0) {
      return zipClasses;
    }
    List<String> classNames = new ArrayList<String>();
    ZipInputStream zip = null;

    try {
      zip = new ZipInputStream(new FileInputStream("plugins/DDCustomPlugin.jar"));
    } catch (FileNotFoundException e) {
      throw new IOException();
    }
    for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry())
      if (entry.getName().endsWith(".class") && !entry.isDirectory()) {
        // This ZipEntry represents a class. Now, what class does it represent?
        StringBuilder className = new StringBuilder();
        for (String part : entry.getName().split("/")) {
          if (className.length() != 0) className.append(".");
          className.append(part);
          if (part.endsWith(".class")) className.setLength(className.length() - ".class".length());
        }
        if (className.toString().indexOf("$") == -1) classNames.add(className.toString());
      }
    zipClasses = classNames;
    return classNames;
  }
コード例 #20
0
 /* shamelessly copied from PlugInManager */
 private static Class toClass(ZipEntry entry, ClassLoader classLoader) {
   if (entry.isDirectory()) {
     return null;
   }
   if (!entry.getName().endsWith(".class")) {
     return null;
   }
   if (entry.getName().indexOf("$") != -1) {
     // I assume it's not necessary to load inner classes explicitly.
     // [Jon Aquino]
     return null;
   }
   String className = entry.getName();
   className = className.substring(0, className.length() - ".class".length());
   className = StringUtil.replaceAll(className, "/", ".");
   Class candidate;
   try {
     candidate = classLoader.loadClass(className);
   } catch (ClassNotFoundException e) {
     Assert.shouldNeverReachHere(
         "Class not found: " + className + ". Refine class name algorithm.");
     return null;
   } catch (Throwable t) {
     LOG.error("Throwable encountered loading " + className + ":");
     // e.g. java.lang.VerifyError: class
     // org.apache.xml.serialize.XML11Serializer
     // overrides final method [Jon Aquino]
     t.printStackTrace(System.out);
     return null;
   }
   return candidate;
 }
コード例 #21
0
ファイル: FsEntry.java プロジェクト: DarioGT/OMS-PluginXML
  public String getSimpleName() {
    String name;

    if (m_file != null) {
      name = m_file.getName();
    } else if (m_entry != null) {
      String entryName = m_entry.getName();

      if (m_entry.isDirectory()) {
        int len = entryName.length();
        int idx = entryName.lastIndexOf('/', len - 2);
        name = (idx == -1) ? entryName : entryName.substring(idx + 1, len - 1);
      } else {
        int idx = entryName.lastIndexOf('/');
        name = (idx == -1) ? entryName : entryName.substring(idx + 1);
      }
    } else if (m_composite != null) {
      name = m_composite.getName();
      // name = m_url.getFile();
    } else {
      name = "???";
    } // end if

    return name;
  }
コード例 #22
0
ファイル: ZipUtils.java プロジェクト: paraita/scheduling
 /**
  * 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));
         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();
         out.close();
         in.close();
       }
     }
   } else {
     throw new IOException(
         "Destination " + dest.getAbsolutePath() + " is not a directory or does not exist");
   }
 }
コード例 #23
0
 public static void unZip(String unZipfileName, String mDestPath) {
   if (!mDestPath.endsWith("/")) {
     mDestPath = mDestPath + "/";
   }
   FileOutputStream fileOut = null;
   ZipInputStream zipIn = null;
   ZipEntry zipEntry = null;
   File file = null;
   int readedBytes = 0;
   byte buf[] = new byte[4096];
   try {
     zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)));
     while ((zipEntry = zipIn.getNextEntry()) != null) {
       file = new File(mDestPath + zipEntry.getName());
       if (zipEntry.isDirectory()) {
         file.mkdirs();
       } else {
         // 如果指定文件的目录不存在,则创建之.
         File parent = file.getParentFile();
         if (!parent.exists()) {
           parent.mkdirs();
         }
         fileOut = new FileOutputStream(file);
         while ((readedBytes = zipIn.read(buf)) > 0) {
           fileOut.write(buf, 0, readedBytes);
         }
         fileOut.close();
       }
       zipIn.closeEntry();
     }
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
コード例 #24
0
ファイル: Zip批量解压.java プロジェクト: gcshi/Java
  /**
   * 真正的解压方法 会删除解压完的所有Zip文档
   *
   * @param File 一个。zip的 文件
   */
  public static void myzijide(File file) throws IOException {

    ZipInputStream zip = new ZipInputStream(new FileInputStream(file));
    ZipEntry en = null;
    BufferedOutputStream out = null;
    // 循环读取ZIP文件中的内容
    while ((en = zip.getNextEntry()) != null) {
      if (en.isDirectory()) {
        File f = new File(file.getParent() + "\\" + en.getName());
        if (!f.exists()) f.mkdirs();
        continue;
      }
      // 发现好多文件夹存在 Thumbs , 定一个识别将他过滤
      //  文件名中含有Thumbs 将 不 解压
      if (en.getName().contains("Thumbs")) {
        continue;
      }

      // 实际的输出方法
      out = new BufferedOutputStream(new FileOutputStream(file.getParent() + "\\" + en.getName()));

      int i = -1;
      byte[] b = new byte[1024];
      while ((i = zip.read(b)) != -1) {
        out.write(b, 0, i);
      }
      out.close();
    }
    zip.close();

    // 删除文件
    String tishi = file.delete() ? "yes" : "no";
    System.out.println(file.getName() + "解压完成并删除 ?" + tishi);
  }
コード例 #25
0
ファイル: ArchiveExtractTo.java プロジェクト: BaseXdb/basex
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    checkCreate(qc);

    final Path path = toPath(0, qc);
    final B64 archive = toB64(exprs[1], qc, false);
    final TokenSet hs = entries(2, qc);

    try (ArchiveIn in = ArchiveIn.get(archive.input(info), info)) {
      while (in.more()) {
        final ZipEntry ze = in.entry();
        final String name = ze.getName();
        if (hs == null || hs.delete(token(name)) != 0) {
          final Path file = path.resolve(name);
          if (ze.isDirectory()) {
            Files.createDirectories(file);
          } else {
            Files.createDirectories(file.getParent());
            Files.write(file, in.read());
          }
        }
      }
    } catch (final IOException ex) {
      throw ARCH_FAIL_X.get(info, ex);
    }
    return null;
  }
コード例 #26
0
 public static void unzip(File dest, String jar) throws IOException {
   dest.mkdirs();
   ZipFile zf = new ZipFile(jar);
   try {
     Enumeration es = zf.entries();
     while (es.hasMoreElements()) {
       ZipEntry je = (ZipEntry) es.nextElement();
       String n = je.getName();
       File f = new File(dest, n);
       if (je.isDirectory()) {
         f.mkdirs();
       } else {
         if (f.exists()) {
           f.delete();
         } else {
           f.getParentFile().mkdirs();
         }
         InputStream is = zf.getInputStream(je);
         FileOutputStream os = new FileOutputStream(f);
         try {
           copyStream(is, os);
         } finally {
           os.close();
         }
       }
       long time = je.getTime();
       if (time != -1) f.setLastModified(time);
     }
   } finally {
     zf.close();
   }
 }
コード例 #27
0
ファイル: Zips.java プロジェクト: jinahya/jinahya-se
  /**
   * Unzips entries from {@code stream} into {@code directory}.
   *
   * @param stream source zip stream
   * @param directory target directory to which entries going to be unzipped.
   * @param buffer the buffer to use
   * @throws IOException if an I/O error occurs.
   */
  public static void unzip(final ZipInputStream stream, final File directory, final byte[] buffer)
      throws IOException {

    if (stream == null) {
      throw new NullPointerException("stream");
    }

    if (directory == null) {
      throw new NullPointerException("directory");
    }

    if (!directory.isDirectory()) {
      throw new IllegalArgumentException("directory doesn't exist");
    }

    if (buffer == null) {
      throw new NullPointerException("buffer");
    }

    if (buffer.length == 0) {
      throw new IllegalArgumentException("buffer.length(" + buffer.length + ") == 0");
    }

    ZipEntry entry;
    while ((entry = stream.getNextEntry()) != null) {
      final File file = file(directory, entry);
      if (!entry.isDirectory()) {
        ByteStreams.copy(stream, file, buffer, -1L);
      }
      stream.closeEntry();
    }
  }
コード例 #28
0
ファイル: SDKDownloader.java プロジェクト: Hilzu/kotlin
  protected void unzip(String pathToFile, String outputFolder) {
    System.out.println("Start unzipping: " + pathToFile + " to " + outputFolder);
    String pathToUnzip;
    if (outputFolder.equals(pathManager.getPlatformFolderInAndroidSdk())) {
      pathToUnzip = outputFolder;
    } else {
      pathToUnzip = outputFolder + "/" + FileUtil.getNameWithoutExtension(new File(pathToFile));
    }
    if (new File(pathToUnzip).listFiles() != null) {
      System.out.println("File was already unzipped: " + pathToFile);
      return;
    }
    try {
      byte[] buf = new byte[1024];
      ZipInputStream zipinputstream = null;
      ZipEntry zipentry;
      zipinputstream = new ZipInputStream(new FileInputStream(pathToFile));

      zipentry = zipinputstream.getNextEntry();
      try {
        while (zipentry != null) {
          String entryName = zipentry.getName();
          int n;
          File outputFile = new File(outputFolder + "/" + entryName);

          if (zipentry.isDirectory()) {
            outputFile.mkdirs();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
            continue;
          } else {
            File parentFile = outputFile.getParentFile();
            if (parentFile != null && !parentFile.exists()) {
              parentFile.mkdirs();
            }
            outputFile.createNewFile();
          }

          FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
          try {
            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
              fileoutputstream.write(buf, 0, n);
            }
          } finally {
            fileoutputstream.close();
          }
          zipinputstream.closeEntry();
          zipentry = zipinputstream.getNextEntry();
        }

        zipinputstream.close();
      } catch (IOException e) {
        System.err.println("Entry name: " + zipentry.getName());
        e.printStackTrace();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("Finish unzipping: " + pathToFile + " to " + outputFolder);
  }
コード例 #29
0
  private void removePreviousModVersion(String modName, String installedVersion) {
    try {
      // Mod has been previously installed uninstall previous version
      File previousModZip = new File(cacheDir, modName + "-" + installedVersion + ".zip");
      ZipFile zf = new ZipFile(previousModZip);
      Enumeration<? extends ZipEntry> entries = zf.entries();
      // Go through zipfile of previous version and delete all file from
      // Modpack that exist in the zip
      while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (entry.isDirectory()) {
          continue;
        }
        File file = new File(GameUpdater.modpackDir, entry.getName());
        Util.log("Deleting '%s'", entry.getName());
        if (file.exists()) {
          // File from mod exists.. delete it
          file.delete();
        }
      }

      InstalledModsYML.removeMod(modName);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #30
0
ファイル: Archive.java プロジェクト: Kwakjeonghwan/smooks
  /**
   * Add the entries from the supplied {@link ZipInputStream} to this archive instance.
   *
   * @param zipStream The zip stream.
   * @return This archive instance.
   * @throws IOException Error reading zip stream.
   */
  public Archive addEntries(ZipInputStream zipStream) throws IOException {
    AssertArgument.isNotNull(zipStream, "zipStream");

    try {
      ZipEntry zipEntry = zipStream.getNextEntry();
      ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
      byte[] byteReadBuffer = new byte[512];
      int byteReadCount;

      while (zipEntry != null) {
        if (zipEntry.isDirectory()) {
          addEntry(zipEntry.getName(), (byte[]) null);
        } else {
          while ((byteReadCount = zipStream.read(byteReadBuffer)) != -1) {
            outByteStream.write(byteReadBuffer, 0, byteReadCount);
          }
          addEntry(zipEntry.getName(), outByteStream.toByteArray());
          outByteStream.reset();
        }
        zipEntry = zipStream.getNextEntry();
      }
    } finally {
      try {
        zipStream.close();
      } catch (IOException e) {
        logger.debug("Unexpected error closing EDI Mapping Model Zip stream.", e);
      }
    }

    return this;
  }