Java Code Examples for java.util.zip.ZipFile#getInputStream()

The following examples show how to use java.util.zip.ZipFile#getInputStream() . 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 File: FileUtils.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Unzips zip file
 * @param zipFile Zip file
 * @param dir Directory to place unzipped files
 * @throws IOException Thrown when unzipping fails
 */
public static void unzip(ZipFile zipFile, File dir) throws IOException{
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while(entries.hasMoreElements()){
        ZipEntry entry = entries.nextElement();
        File zipChild = new File(dir, entry.getName());

        if (entry.isDirectory()){
            zipChild.mkdirs();
        }else{
            zipChild.getParentFile().mkdirs();
            InputStream in = zipFile.getInputStream(entry);
            Files.copy(in, Paths.get(zipChild.toURI()));
            in.close();
        }
    }

    zipFile.close();
}
 
Example 2
Source File: P4JavaTestCase.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Unpack an archive file's content onto a destination folder.
 */
public static void unpack(File zipFile, File destDir) throws IOException {
	ZipFile zip = new ZipFile(zipFile);
	Enumeration<? extends ZipEntry> entries = zip.entries();
	while (entries.hasMoreElements()) {
		ZipEntry entry = entries.nextElement();
		File f = new File(destDir, entry.getName());
		if (entry.isDirectory()) {
			continue;
		}
		if (!f.exists()) {
			f.getParentFile().mkdirs();
			f.createNewFile();
		}
		InputStream is = zip.getInputStream(entry);
		OutputStream os = new FileOutputStream(f);
		byte[] buf = new byte[4096];
		int r;
		while ((r = is.read(buf)) != -1) {
			os.write(buf, 0, r);
		}
		os.close();
		is.close();
	}
}
 
Example 3
Source File: URLUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static InputStream openJarStream(@Nonnull URL url) throws IOException {
  Pair<String, String> paths = splitJarUrl(url.getFile());
  if (paths == null) {
    throw new MalformedURLException(url.getFile());
  }

  @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final ZipFile zipFile = new ZipFile(paths.first);
  ZipEntry zipEntry = zipFile.getEntry(paths.second);
  if (zipEntry == null) {
    zipFile.close();
    throw new FileNotFoundException("Entry " + paths.second + " not found in " + paths.first);
  }

  return new FilterInputStream(zipFile.getInputStream(zipEntry)) {
    @Override
    public void close() throws IOException {
      super.close();
      zipFile.close();
    }
  };
}
 
Example 4
Source File: PathUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void unzip(final ZipFile zip, final Path targetDir) throws IOException {
    final Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        final String name = entry.getName();
        final Path current = resolveSecurely(targetDir, name);
        if (entry.isDirectory()) {
            if (!Files.exists(current)) {
                Files.createDirectories(current);
            }
        } else {
            if (Files.notExists(current.getParent())) {
                Files.createDirectories(current.getParent());
            }
            try (final InputStream eis = zip.getInputStream(entry)) {
                Files.copy(eis, current);
            }
        }
        try {
            Files.getFileAttributeView(current, BasicFileAttributeView.class).setTimes(entry.getLastModifiedTime(), entry.getLastAccessTime(), entry.getCreationTime());
        } catch (IOException e) {
            //ignore, if we cannot set it, world will not end
        }
    }
}
 
Example 5
Source File: FileUtils.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void extractZipEntryToStream(  ZipFile zipFile, String entryName, OutputStream outputStream) throws ZipEntryNotFoundException, IOException {
	
	if( logger.isDebugEnabled()) {
		logger.debug( "Transferring ZIP entry " + entryName + " from ZIP file " + zipFile.getName() + " to stream");
	}
	
	ZipEntry zipEntry = zipFile.getEntry( entryName);
	
	if( zipEntry == null) {
		logger.info( "ZIP entry not found: " + entryName);
		
		throw new ZipEntryNotFoundException( entryName);
	}
	
	try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
		streamToStream( inputStream, zipEntry.getSize(), outputStream);
	}
}
 
Example 6
Source File: XlsxSheetContentParser.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Closes the current open {@link XMLStreamReader} and creates a new one which starts the
 * reading process at the first row. It is assumed the the XLSX content and operator
 * configuration remain the same.
 *
 * @param xmlFactory
 *            the {@link XMLInputFactory} that should be used to open the
 *            {@link XMLStreamReader}.
 *
 * @throws IOException
 *             if an I/O error has occurred
 * @throws XMLStreamException
 *             if there are errors freeing associated XML reader resources or creating a new XML
 *             reader
 */
void reset(XMLInputFactory xmlFactory) throws IOException, XMLStreamException {

	// close open file and reader object
	close();

	// create new file and stream reader objects
	xlsxZipFile = new ZipFile(xlsxFile);
	ZipEntry workbookZipEntry = xlsxZipFile.getEntry(workbookZipEntryPath);
	if (workbookZipEntry == null) {
		throw new FileNotFoundException(
				"XLSX file is malformed. Reason: Selected workbook is missing in XLSX file. Path: "
						+ workbookZipEntryPath);
	}
	InputStream inputStream = xlsxZipFile.getInputStream(workbookZipEntry);
	cis = new CountingInputStream(inputStream);
	reader = xmlFactory.createXMLStreamReader(new InputStreamReader(cis, encoding));

	// reset other variables
	currentRowIndex = -1;
	parsedRowIndex = -1;
	currentRowContent = null;
	nextRowWithContent = null;
	hasMoreContent = true;
	Arrays.fill(emptyColumn, true);
}
 
Example 7
Source File: UpdateManager.java    From developer-studio with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts a jar file to a given directory.
 * 
 * @param jar
 *            Source jar file.
 * @param extractpath
 *            Destination to extract.
 * 
 * @throws IOException
 */
private void extractJar(File jar, File extractpath) throws IOException {
	ZipFile zipFile = new ZipFile(jar);
	try {
		Enumeration<? extends ZipEntry> entries = zipFile.entries();
		while (entries.hasMoreElements()) {
			ZipEntry entry = entries.nextElement();
			File entryDestination = new File(extractpath, entry.getName());
			if (entry.isDirectory())
				entryDestination.mkdirs();
			else {
				entryDestination.getParentFile().mkdirs();
				InputStream in = zipFile.getInputStream(entry);
				OutputStream out = new FileOutputStream(entryDestination);
				IOUtils.copy(in, out);
				IOUtils.closeQuietly(in);
				out.close();
			}
		}
	} finally {
		zipFile.close();
	}
}
 
Example 8
Source File: CSVSwaptionParser.java    From finmath-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a single lattice from streams and save the data in the given convention.
 * The parser will not check that the files are aligned for the same reference date.
 *
 * @param atmZip The zip file containing data on atm swpations.
 * @param atmEntry The entry to use from the atmZip.
 * @param otmZip The zip file containing data on otm swaptions.
 * @param otmEntry The entry to use from the otmZip.
 * @param referenceDate The reference date the swaptions should be created with respect to.
 * @param currency The currency, which should be parsed from the files.
 * @param index The index, which should be parsed from the files.
 * @param discountCurveName The name of the discount curve, which should be used by the swaptions.
 * @param convention The quoting convention to store the data in.
 * @param displacement The displacement to use, if storing in convention VOLATILITYLOGNORMAL
 * @param model The model for context to use when converting data to convention.
 *
 * @return The lattice containing the data from the files.
 *
 * @throws IOException Thrown upon io error with ZipFile.
 */
private SwaptionDataLattice parseStreamsToConvention(final ZipFile atmZip, final ZipEntry atmEntry, final ZipFile otmZip, final ZipEntry otmEntry, final LocalDate referenceDate,
		final String currency, final String index, final String discountCurveName, final QuotingConvention convention, final double displacement, final AnalyticModel model)
				throws IOException {

	//Prepare empty lattice
	SwaptionDataLattice data = new SwaptionDataLattice(referenceDate, convention, displacement, "Forward_"+currency+"_"+index, discountCurveName, floatMetaSchedule, fixMetaSchedule,
			new String[0], new int[0], new double[0]);

	//Add each individual node on the requested maturity x tenor grid.
	for(final String maturity : maturities) {
		for(final String tenor : tenors) {
			final CSVSwaptionParser partialParser = new CSVSwaptionParser(new String[] {maturity}, new String[] {tenor}, fixMetaSchedule, floatMetaSchedule);
			try(InputStream atmStream = atmZip.getInputStream(atmEntry)) {
				try(InputStream otmStream = otmZip.getInputStream(otmEntry)) {
					data = data.append(partialParser.parseStreams(atmStream, otmStream, referenceDate, currency, index, discountCurveName), model);
				}
			}
		}
	}

	return data;
}
 
Example 9
Source File: ZipUtils.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Unzip a zip file into a directory.
 * @param zipFile The zip file to be unzipped.
 * @param dest the destination directory.
 * @throws IOException if the destination does not exist or is not a directory, or if the zip file cannot be extracted.
 */
public static void unzip(ZipFile zipFile, File dest) throws IOException {
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    if (dest.exists() && dest.isDirectory()) {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                File destFile = new File(dest, entry.getName());
                createFileWithPath(destFile);
                InputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
                try (OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile))) {
                    byte[] buffer = new byte[2048];
                    for (;;) {
                        int nBytes = in.read(buffer);
                        if (nBytes <= 0)
                            break;
                        out.write(buffer, 0, nBytes);
                    }
                    out.flush();
                }
                in.close();
            }
        }
    } else {
        throw new IOException("Destination " + dest.getAbsolutePath() + " is not a directory or does not exist");
    }
}
 
Example 10
Source File: JPackagerDownloader.java    From shogun with Apache License 2.0 5 votes vote down vote up
private static void unZip(Path root, Path archiveFile) throws IOException {
    ZipFile zip = new ZipFile(archiveFile.toFile());
    Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (entry.isDirectory()) {
            Files.createDirectories(root.resolve(entry.getName()));
        } else {
            try (InputStream is = new BufferedInputStream(zip.getInputStream(entry))) {
                Files.copy(is, root.resolve(entry.getName()));
            }
        }

    }
}
 
Example 11
Source File: NewProjectWizardIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void copyZipEntry(ZipFile zipFile, ZipEntry zipEntry, File destinationFile) throws IOException {
    if (zipEntry.isDirectory()) {
        return;
    }
    try (InputStream inputStream = zipFile.getInputStream(zipEntry); FileOutputStream outputStream = new FileOutputStream(destinationFile)) {
        FileUtil.copy(inputStream, outputStream);
    }
}
 
Example 12
Source File: AARLibrary.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the package name from the Android Archive without needing to unzip it to a location
 * in the file system
 *
 * @param zip the input stream reading from the Android Archive.
 * @return the package name declared in the archive's AndroidManifest.xml.
 * @throws IOException if reading the input stream fails.
 */
private String extractPackageName(ZipFile zip) throws IOException {
  ZipEntry entry = zip.getEntry("AndroidManifest.xml");
  if (entry == null) {
    throw new IllegalArgumentException(zip.getName() + " does not contain AndroidManifest.xml");
  }
  try {
    ZipEntryWrapper wrapper = new ZipEntryWrapper(zip.getInputStream(entry));
    // the following call will automatically close the input stream opened above
    return AndroidManifest.getPackage(wrapper);
  } catch(StreamException|XPathExpressionException e) {
    throw new IOException("Exception processing AndroidManifest.xml", e);
  }
}
 
Example 13
Source File: ZipResourceLoader.java    From hasor with Apache License 2.0 5 votes vote down vote up
public InputStream getResourceAsStream(String resourcePath) throws IOException {
    if (this.zipFile.isDirectory() || !this.zipFile.exists()) {
        return null;
    }
    //
    resourcePath = formatResourcePath(resourcePath);
    if (!this.zipEntrySet.containsKey(resourcePath)) {
        return null;
    }
    //
    ZipFile zipFileObj = new ZipFile(this.zipFile);
    ZipEntry entry = zipFileObj.getEntry(resourcePath);
    return new ZipEntryInputStream(zipFileObj, zipFileObj.getInputStream(entry));
}
 
Example 14
Source File: FileUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void copyZipEntry(ZipFile zipFile, ZipEntry zipEntry, File destinationFile) throws IOException {
    if (zipEntry.isDirectory()) {
        return;
    }
    try (InputStream inputStream = zipFile.getInputStream(zipEntry); FileOutputStream outputStream = new FileOutputStream(destinationFile)) {
        FileUtil.copy(inputStream, outputStream);
    }
}
 
Example 15
Source File: KarafJavaScriptForESBWithMavenManager.java    From tesb-studio-se with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void addFeatureFileToExport(List<ExportFileResource> list, ExportFileResource[] processes) {
    if (destinationKar != null) {
        File karFile = new File(destinationKar);
        if (karFile.exists()) {
            ProcessItem processItem = (ProcessItem) processes[0].getItem();
            String projectName = getCorrespondingProjectName(processItem);
            String jobName = processItem.getProperty().getLabel();
            String jobVersion = processItem.getProperty().getVersion();
            StringBuilder sb = new StringBuilder();
            sb.append("repository/").append(projectName).append(PATH_SEPARATOR).append(jobName).append(PATH_SEPARATOR); //$NON-NLS-1$
            String featurePath = sb.append(jobName).append("-feature/").append(jobVersion).append(PATH_SEPARATOR) //$NON-NLS-1$
                    .append(jobName).append("-feature-").append(jobVersion).append(".xml").toString(); //$NON-NLS-1$ //$NON-NLS-2$
            ExportFileResource featureFileResource = new ExportFileResource(null, ""); //$NON-NLS-1$
            try {
                ZipFile zipFile = new ZipFile(karFile);
                ZipEntry zipEntry = zipFile.getEntry(featurePath);
                if (zipEntry != null) {
                    InputStream in = null;
                    try {
                        in = zipFile.getInputStream(zipEntry);
                        File featureFile = new File(getTmpFolder() + "feature/feature.xml"); //$NON-NLS-1$
                        FilesUtils.copyFile(in, featureFile);
                        featureFileResource
                                .addResource(IMavenProperties.MAIN_RESOURCES_PATH + "feature", featureFile.toURL()); //$NON-NLS-1$
                    } finally {
                        zipFile.close();
                    }
                }
            } catch (Exception e) {
                ExceptionHandler.process(e);
            }
            list.add(featureFileResource);
        }
    }
}
 
Example 16
Source File: JarSigner.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void writeBytes
        (ZipFile zf, ZipEntry ze, ZipOutputStream os) throws IOException {
    try (InputStream is = zf.getInputStream(ze)) {
        is.transferTo(os);
    }
}
 
Example 17
Source File: PluginManager.java    From weblaf with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns plugin information from the specified plugin file.
 * Returns null in case plugin file cannot be read or if it is incorrect.
 *
 * @param file plugin file to process
 * @return plugin information from the specified plugin file or null
 */
protected DetectedPlugin<P> detectPlugin ( final File file )
{
    try
    {
        final String pluginDescriptor = getPluginDescriptorFile ();
        final String pluginLogo = getPluginLogoFile ();
        final ZipFile zipFile = new ZipFile ( file );
        final Enumeration entries = zipFile.entries ();
        while ( entries.hasMoreElements () )
        {
            final ZipEntry entry = ( ZipEntry ) entries.nextElement ();
            if ( entry.getName ().endsWith ( pluginDescriptor ) )
            {
                // Reading plugin information
                final InputStream inputStream = zipFile.getInputStream ( entry );
                final PluginInformation info = XmlUtils.fromXML ( inputStream );
                inputStream.close ();

                // Reading plugin icon
                final Icon logo;
                if ( !SystemUtils.isHeadlessEnvironment () )
                {
                    final ZipEntry logoEntry = new ZipEntry ( ZipUtils.getFileLocation ( entry ) + pluginLogo );
                    final InputStream logoInputStream = zipFile.getInputStream ( logoEntry );
                    if ( logoInputStream != null )
                    {
                        // todo This will force logo to always be static
                        logo = ImageUtils.toImageIcon ( ImageUtils.loadBufferedImage ( logoInputStream ) );
                        logoInputStream.close ();
                    }
                    else
                    {
                        logo = null;
                    }
                }
                else
                {
                    logo = null;
                }

                // Checking whether we have already detected this plugin or not
                if ( !wasDetected ( file.getParent (), file.getName () ) )
                {
                    // Cache and return new plugin information
                    // This cache map is filled here since it has different usage cases
                    final DetectedPlugin<P> plugin = new DetectedPlugin<P> ( file.getParent (), file.getName (), info, logo );
                    detectedPluginsByPath.put ( FileUtils.canonicalPath ( file ), plugin );
                    return plugin;
                }

                break;
            }
        }
        zipFile.close ();
    }
    catch ( final IOException e )
    {
        LoggerFactory.getLogger ( PluginManager.class ).error ( "Unable to read plugin information", e );
    }
    return null;
}
 
Example 18
Source File: SiteZipper.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Unzip a zip file into the unzip directory. Only unzips the files that are found within the first folder
 * contained in the zip archive.
 * @param zipFilePath Path to ZIP file
 * @param m_unzipPath Path to directory to unzip file into.
 * @return The toplevel directory which the zipfile created.
 * @throws IOException
 */
public String unzipArchive(String zipFilePath, String m_unzipPath) throws IOException {
	
	log.debug("zipFilePath: " + zipFilePath);

	ZipFile zipFile = new ZipFile(zipFilePath);
	// Default path from the filename.
	String unzippedArchivePath = null;
	Enumeration<? extends ZipEntry> entries = zipFile.entries();
	while (entries.hasMoreElements()) {
		ZipEntry entry = entries.nextElement();

		//destination file from zip. Straight into the normal archive directory
		File dest = new File(m_unzipPath, entry.getName());
		log.debug("Dest: " + dest.getAbsolutePath());

		if(entry.isDirectory()) {
			//create dir
			if(!dest.mkdir()) {
				throw new IOException("Failed to create directory "+ dest);
			}
			if (unzippedArchivePath == null) {
				unzippedArchivePath = entry.getName();
			}

		} else if (unzippedArchivePath != null && entry.getName().startsWith(unzippedArchivePath)){
			//extract contents
			try (InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(dest)) {
				IOUtils.copy(in, out);
			}
		} else {
			log.info("Ignoring entry: {}", entry.getName());
		}
	}
	
	//get original filename, remove timestamp, add -archive

	log.debug("unzippedArchivePath: " + unzippedArchivePath);

	return unzippedArchivePath;
}
 
Example 19
Source File: TextFileOutputIT.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the ZIP output capability of the TextFileOutput step
 *
 * @throws Exception
 */
@Test
public void testTextFileOutput4() throws Exception {
  KettleEnvironment.init();

  // Create a new transformation...
  //
  TransMeta transMeta = new TransMeta();
  transMeta.setName( "testTextFileOutput4" );
  PluginRegistry registry = PluginRegistry.getInstance();

  // create an injector step
  String injectorStepName = "injector step";
  StepMeta injectorStep = TestUtilities.createInjectorStep( injectorStepName, registry );
  transMeta.addStep( injectorStep );

  // create a row generator step
  StepMeta rowGeneratorStep = createRowGeneratorStep( "Create rows for testTextFileOutput4", registry );
  transMeta.addStep( rowGeneratorStep );

  // create a TransHopMeta for injector and add it to the transMeta
  TransHopMeta hop_injectory_rowGenerator = new TransHopMeta( injectorStep, rowGeneratorStep );
  transMeta.addTransHop( hop_injectory_rowGenerator );

  // create the text file output step with ZIP compression
  // but first lets get a filename
  String textFileName = "testTextFileOutput4";
  String textFileOutputStepName = "text file output step";
  StepMeta textFileOutputStep = createTextFileOutputStep( textFileOutputStepName, textFileName, "Zip", registry );
  transMeta.addStep( textFileOutputStep );

  // create a TransHopMeta for textFileOutputStep and add it to the transMeta
  TransHopMeta hop_RowGenerator_outputTextFile = new TransHopMeta( rowGeneratorStep, textFileOutputStep );
  transMeta.addTransHop( hop_RowGenerator_outputTextFile );

  // Now execute the transformation...
  Trans trans = new Trans( transMeta );
  trans.prepareExecution( null );

  // Create a row collector and add it to the dummy step interface
  StepInterface dummyStepInterface = trans.getStepInterface( textFileOutputStepName, 0 );
  RowStepCollector dummyRowCollector = new RowStepCollector();
  dummyStepInterface.addRowListener( dummyRowCollector );

  trans.startThreads();
  trans.waitUntilFinished();

  // Compare the results
  List<RowMetaAndData> resultRows = dummyRowCollector.getRowsWritten();
  Object[][] rows = new Object[10][3];
  File f = new File( textFileName + ".zip" );
  f.deleteOnExit();
  try {
    ZipFile zf = new ZipFile( f );
    int zipEntryCount = 0;
    Enumeration<? extends ZipEntry> entries = zf.entries();

    while ( entries.hasMoreElements() ) {
      ZipEntry ze = entries.nextElement();
      zipEntryCount++;
      BufferedReader input = new BufferedReader( new InputStreamReader( zf.getInputStream( ze ) ) );
      readData1Rows( rows, input );
    }

    zf.close();
    assertEquals( zipEntryCount, 1 );

  } catch ( IOException e ) {
    fail( e.getLocalizedMessage() );
  }

  List<RowMetaAndData> outFileRows = createResultDataFromObjects( rows );

  try {
    TestUtilities.checkRows( resultRows, outFileRows );
  } catch ( TestFailedException tfe ) {
    fail( tfe.getMessage() );
  }
}
 
Example 20
Source File: Zip.java    From DexEncryptionDecryption with Apache License 2.0 4 votes vote down vote up
/**
 * 解压zip文件至dir目录
 * @param zip
 * @param dir
 */
public static void unZip(File zip, File dir) {
    try {
        deleteFile(dir);
        ZipFile zipFile = new ZipFile(zip);
        //zip文件中每一个条目
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        //遍历
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            //zip中 文件/目录名
            String name = zipEntry.getName();
            //原来的签名文件 不需要了
            if (name.equals("META-INF/CERT.RSA") || name.equals("META-INF/CERT.SF") || name
                    .equals("META-INF/MANIFEST.MF")) {
                continue;
            }
            //空目录不管
            if (!zipEntry.isDirectory()) {
                File file = new File(dir, name);
                //创建目录
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                //写文件
                FileOutputStream fos = new FileOutputStream(file);
                InputStream is = zipFile.getInputStream(zipEntry);
                byte[] buffer = new byte[2048];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
            }
        }
        zipFile.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}