为您推荐:
精华内容
最热下载
问答
  • 本文整理匯總了Java中org.apache.commons.compress.archivers.zip.ZipFile.getEntries方法的典型用法代碼示例。如果您正苦於以下問題:Java ZipFile.getEntries方法的具體用法?Java ZipFile.getEntries怎麽用?Java...

    本文整理匯總了Java中org.apache.commons.compress.archivers.zip.ZipFile.getEntries方法的典型用法代碼示例。如果您正苦於以下問題:Java ZipFile.getEntries方法的具體用法?Java ZipFile.getEntries怎麽用?Java ZipFile.getEntries使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.apache.commons.compress.archivers.zip.ZipFile的用法示例。

    在下文中一共展示了ZipFile.getEntries方法的30個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Java代碼示例。

    示例1: extractZip

    ​點讚 4

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    private void extractZip(ZipFile zipFile) {

    Enumeration entries = zipFile.getEntries();

    while (entries.hasMoreElements()) {

    ZipArchiveEntry entry = entries.nextElement();

    String fileName = entry.getName();

    File outputFile = new File(config.getExtractionFolder(), fileName);

    if (entry.isDirectory()) {

    makeDirectory(outputFile);

    } else {

    createNewFile(outputFile);

    try {

    InputStream inputStream = zipFile.getInputStream(entry);

    extractFile(inputStream, outputFile, fileName);

    } catch (IOException e) {

    throw new ExtractionException("Error extracting file '" + fileName + "' "

    + "from downloaded file: " + config.getDownloadTarget(), e);

    }

    }

    }

    }

    開發者ID:AlejandroRivera,項目名稱:embedded-rabbitmq,代碼行數:23,

    示例2: TestBarInstaller

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * barファイル內エントリのファイルサイズ上限値を超えた場合に例外が発生すること.

    */

    @Test

    public void barファイル內エントリのファイルサイズ上限値を超えた場合に例外が発生すること() {

    TestBarInstaller testBarInstaller = new TestBarInstaller();

    URL fileUrl = ClassLoader.getSystemResource("requestData/barInstall/V1_1_2_bar_minimum.bar");

    File file = new File(fileUrl.getPath());

    try {

    ZipFile zipFile = new ZipFile(file, "UTF-8");

    Enumeration entries = zipFile.getEntries();

    long maxBarEntryFileSize = 0;

    while (entries.hasMoreElements()) {

    ZipArchiveEntry zae = entries.nextElement();

    if (zae.isDirectory()) {

    continue;

    }

    testBarInstaller.checkBarFileEntrySize(zae, zae.getName(), maxBarEntryFileSize);

    }

    fail("Unexpected exception");

    } catch (PersoniumCoreException dce) {

    String code = PersoniumCoreException.BarInstall.BAR_FILE_ENTRY_SIZE_TOO_LARGE.getCode();

    assertEquals(code, dce.getCode());

    } catch (Exception ex) {

    fail("Unexpected exception");

    }

    }

    開發者ID:personium,項目名稱:personium-core,代碼行數:29,

    示例3: unZipToFolder

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * 把一個ZIP文件解壓到一個指定的目錄中

    * @param zipfilename ZIP文件抽象地址

    * @param outputdir 目錄絕對地址

    */

    public static void unZipToFolder(String zipfilename, String outputdir) throws IOException {

    File zipfile = new File(zipfilename);

    if (zipfile.exists()) {

    outputdir = outputdir + File.separator;

    FileUtils.forceMkdir(new File(outputdir));

    ZipFile zf = new ZipFile(zipfile, "UTF-8");

    Enumeration zipArchiveEntrys = zf.getEntries();

    while (zipArchiveEntrys.hasMoreElements()) {

    ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) zipArchiveEntrys.nextElement();

    if (zipArchiveEntry.isDirectory()) {

    FileUtils.forceMkdir(new File(outputdir + zipArchiveEntry.getName() + File.separator));

    } else {

    IOUtils.copy(zf.getInputStream(zipArchiveEntry), FileUtils.openOutputStream(new File(outputdir + zipArchiveEntry.getName())));

    }

    }

    } else {

    throw new IOException("指定的解壓文件不存在:\t" + zipfilename);

    }

    }

    開發者ID:h819,項目名稱:spring-boot,代碼行數:26,

    示例4: getHashesFromZipFile

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    public List getHashesFromZipFile(File file) throws IOException {

    List hashes = new ArrayList<>();

    ZipFile zipFile = new ZipFile(file);

    byte[] buf = new byte[65536];

    Enumeration> entries = zipFile.getEntries();

    while (entries.hasMoreElements()) {

    ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) entries.nextElement();

    int n;

    InputStream is = zipFile.getInputStream(zipArchiveEntry);

    ZipArchiveInputStream zis = new ZipArchiveInputStream(is);

    if (zis.canReadEntryData(zipArchiveEntry)) {

    while ((n = is.read(buf)) != -1) {

    if (n > 0) {

    hashes.add(DigestUtils.md5Hex(buf));

    }

    }

    }

    zis.close();

    }

    return hashes;

    }

    開發者ID:sysunite,項目名稱:excel-microservice,代碼行數:25,

    示例5: extractZipFile

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    private static void extractZipFile(final File destination, final ZipFile zipFile) throws IOException {

    final Enumeration entries = zipFile.getEntries();

    while (entries.hasMoreElements()) {

    final ZipArchiveEntry entry = entries.nextElement();

    final File entryDestination = new File(destination, entry.getName());

    if (entry.isDirectory()) {

    entryDestination.mkdirs();

    } else {

    entryDestination.getParentFile().mkdirs();

    final InputStream in = zipFile.getInputStream(entry);

    try (final OutputStream out = new FileOutputStream(entryDestination)) {

    IOUtils.copy(in, out);

    IOUtils.closeQuietly(in);

    }

    }

    }

    }

    開發者ID:awslabs,項目名稱:aws-codepipeline-plugin-for-jenkins,代碼行數:20,

    示例6: makeTargetZipFile

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * Writes a modified version of zip_Source into target.

    *

    * @author S3460

    * @param zipSource the zip source

    * @param target the target

    * @return the zip file

    * @throws Exception the exception

    */

    private ZipFile makeTargetZipFile(ZipFile zipSource, File target) throws Exception {

    ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(target));

    for (Enumeration enumer = zipSource.getEntries(); enumer.hasMoreElements();) {

    ZipArchiveEntry sourceEntry = enumer.nextElement();

    out.putArchiveEntry(new ZipArchiveEntry(sourceEntry.getName()));

    byte[] oldBytes = toBytes(zipSource, sourceEntry);

    byte[] newBytes = getRandomBytes();

    byte[] mixedBytes = mixBytes(oldBytes, newBytes);

    out.write(mixedBytes, 0, mixedBytes.length);

    out.flush();

    out.closeArchiveEntry();

    }

    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + entryMaxSize + 1));

    byte[] bytes = getRandomBytes();

    out.write(bytes, 0, bytes.length);

    out.flush();

    out.closeArchiveEntry();

    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + (entryMaxSize + 2)));

    out.closeArchiveEntry();

    out.flush();

    out.finish();

    out.close();

    return new ZipFile(targetFile);

    }

    開發者ID:NitorCreations,項目名稱:javaxdelta,代碼行數:34,

    示例7: compareFiles

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * Compares the content of two zip files. The zip files are considered equal, if

    * the content of all zip entries is equal to the content of its corresponding entry

    * in the other zip file.

    *

    * @author S3460

    * @param zipSource the zip source

    * @param resultZip the result zip

    * @throws Exception the exception

    */

    private void compareFiles(ZipFile zipSource, ZipFile resultZip) throws Exception {

    boolean rc = false;

    try {

    for (Enumeration enumer = zipSource.getEntries(); enumer.hasMoreElements();) {

    ZipArchiveEntry sourceEntry = enumer.nextElement();

    ZipArchiveEntry resultEntry = resultZip.getEntry(sourceEntry.getName());

    assertNotNull("Entry nicht generiert: " + sourceEntry.getName(), resultEntry);

    byte[] oldBytes = toBytes(zipSource, sourceEntry);

    byte[] newBytes = toBytes(resultZip, resultEntry);

    rc = equal(oldBytes, newBytes);

    assertTrue("bytes the same " + sourceEntry, rc);

    }

    } finally {

    zipSource.close();

    resultZip.close();

    }

    }

    開發者ID:NitorCreations,項目名稱:javaxdelta,代碼行數:28,

    示例8: detectKmz

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    private static MediaType detectKmz(ZipFile zip) {

    boolean kmlFound = false;

    Enumeration entries = zip.getEntries();

    while (entries.hasMoreElements()) {

    ZipArchiveEntry entry = entries.nextElement();

    String name = entry.getName();

    if (!entry.isDirectory()

    && name.indexOf('/') == -1 && name.indexOf('\\') == -1) {

    if (name.endsWith(".kml") && !kmlFound) {

    kmlFound = true;

    } else {

    return null;

    }

    }

    }

    if (kmlFound) {

    return MediaType.application("vnd.google-earth.kmz");

    } else {

    return null;

    }

    }

    開發者ID:kolbasa,項目名稱:OCRaptor,代碼行數:24,

    示例9: detectIpa

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @SuppressWarnings("unchecked")

    private static MediaType detectIpa(ZipFile zip) {

    // Note - consider generalising this logic, if another format needs many regexp matching

    Set tmpPatterns = (Set)ipaEntryPatterns.clone();

    Enumeration entries = zip.getEntries();

    while (entries.hasMoreElements()) {

    ZipArchiveEntry entry = entries.nextElement();

    String name = entry.getName();

    Iterator ip = tmpPatterns.iterator();

    while (ip.hasNext()) {

    if (ip.next().matcher(name).matches()) {

    ip.remove();

    }

    }

    if (tmpPatterns.isEmpty()) {

    // We've found everything we need to find

    return MediaType.application("x-itunes-ipa");

    }

    }

    // If we get here, not all required entries were found

    return null;

    }

    開發者ID:kolbasa,項目名稱:OCRaptor,代碼行數:26,

    示例10: testEmptyBaseDirRelativeDir

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @Test

    public void testEmptyBaseDirRelativeDir() throws Exception {

    String aTargetFilename = "target/Z6-input.zip";

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();

    aTasklet.setSourceBaseDirectory(new FileSystemResource(""));

    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();

    aSourceFactory.setPattern("file:src/test/resources/testFiles/input.csv");

    aTasklet.setSourceFactory(aSourceFactory );

    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();

    aDestinationFactory.setExpression(aTargetFilename);

    aTasklet.setDestinationFactory(aDestinationFactory );

    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(null, null));

    assertTrue(new File(aTargetFilename).exists());

    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));

    Enumeration aEntries = aZipFile.getEntries();

    assertTrue(aEntries.hasMoreElements());

    assertEquals("src/test/resources/testFiles/input.csv", aEntries.nextElement().getName());

    assertFalse(aEntries.hasMoreElements());

    aZipFile.close();

    }

    開發者ID:acxio,項目名稱:AGIA,代碼行數:23,

    示例11: readFirstZipEntry

    ​點讚 3

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * Reads the first file entry in a zip file and returns it's contents

    * as uncompressed byte-array

    * @param zipFile the zip file to read from

    * @return the first file entry (uncompressed)

    * @throws IOException if there is an error accessing the zip file

    */

    public static byte[] readFirstZipEntry(File zipFile) throws IOException {

    // open zip

    ZipFile zf = new ZipFile(zipFile);

    Enumeration entries = zf.getEntries();

    // read first entry to byte[]

    ZipArchiveEntry entry = entries.nextElement();

    InputStream is = zf.getInputStream(entry);

    byte[] raw = ByteStreams.toByteArray(is);

    // close all streams and return byte[]

    is.close();

    zf.close();

    return raw;

    }

    開發者ID:klamann,項目名稱:maps4cim,代碼行數:23,

    示例12: unzip

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    public static void unzip(File zipFile, File destination)

    throws IOException {

    ZipFile zip = new ZipFile(zipFile);

    try {

    Enumeration e = zip.getEntries();

    while (e.hasMoreElements()) {

    ZipArchiveEntry entry = e.nextElement();

    File file = new File(destination, entry.getName());

    if (entry.isDirectory()) {

    file.mkdirs();

    } else {

    InputStream is = zip.getInputStream(entry);

    File parent = file.getParentFile();

    if (parent != null && parent.exists() == false) {

    parent.mkdirs();

    }

    FileOutputStream os = new FileOutputStream(file);

    try {

    IOUtils.copy(is, os);

    } finally {

    os.close();

    is.close();

    }

    file.setLastModified(entry.getTime());

    int mode = entry.getUnixMode();

    if ((mode & EXEC_MASK) != 0) {

    if (!file.setExecutable(true)) {

    }

    }

    }

    }

    } finally {

    ZipFile.closeQuietly(zip);

    }

    }

    開發者ID:NBANDROIDTEAM,項目名稱:NBANDROID-V2,代碼行數:36,

    示例13: unzipToTemporaryDirectory

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    public static Path unzipToTemporaryDirectory(File file) throws IOException {

    ZipFile zipFile = new ZipFile(file);

    Enumeration zipEntries = zipFile.getEntries();

    Path tempDirectory = Files.createTempDirectory("temp");

    while (zipEntries.hasMoreElements()) {

    ZipArchiveEntry entry = zipEntries.nextElement();

    FileUtils.copyInputStreamToFile(zipFile.getInputStream(entry), new File(Paths.get(tempDirectory.toString(),"/" + entry.getName()).toString()));

    }

    zipFile.close();

    return tempDirectory;

    }

    開發者ID:FutureCitiesCatapult,項目名稱:TomboloDigitalConnector,代碼行數:13,

    示例14: extractAll

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    public static void extractAll(String zipFile, String extractDir) throws Exception {

    ZipFile unzipFile = new ZipFile(zipFile);

    try {

    File root = new File(extractDir);

    Enumeration fileHeaderList = unzipFile.getEntries();

    while(fileHeaderList.hasMoreElements()) {

    ZipArchiveEntry fileHeader = fileHeaderList.nextElement();

    if (fileHeader.isDirectory()) {

    //...

    } else if (!fileHeader.isUnixSymlink()) {

    File f = new File(root, fileHeader.getName());

    File dir = f.getParentFile();

    if (!dir.exists()) {

    dir.mkdirs();

    }

    FileOutputStream fout = new FileOutputStream(f);

    try {

    IOUtils.copy(unzipFile.getInputStream(fileHeader), fout);

    } finally {

    try {

    fout.close();

    } catch (Throwable e) {

    }

    }

    f.setLastModified(fileHeader.getLastModifiedDate().getTime());

    }

    }

    } finally {

    ZipFile.closeQuietly(unzipFile);

    }

    }

    開發者ID:BeckYang,項目名稱:TeamFileList,代碼行數:32,

    示例15: decompressZip

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    public void decompressZip(File zipFile, String dir) throws IOException {

    ZipFile zf = new ZipFile(zipFile);

    try {

    for (Enumeration entries = zf.getEntries(); entries

    .hasMoreElements();) {

    ZipArchiveEntry ze = entries.nextElement();

    // 不存在則創建目標文件夾。

    File targetFile = new File(dir, ze.getName());

    // 遇到根目錄時跳過。

    if (ze.getName().lastIndexOf("/") == (ze.getName().length() - 1)) {

    continue;

    }

    // 如果文件夾不存在,創建文件夾。

    if (!targetFile.getParentFile().exists()) {

    targetFile.getParentFile().mkdirs();

    }

    InputStream i = zf.getInputStream(ze);

    OutputStream o = null;

    try {

    o = new FileOutputStream(targetFile);

    IOUtils.copy(i, o);

    } finally {

    if (i != null) {

    i.close();

    }

    if (o != null) {

    o.close();

    }

    }

    }

    } finally {

    zf.close();

    }

    }

    開發者ID:hoozheng,項目名稱:AndroidRobot,代碼行數:36,

    示例16: readZip

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    public ZipArchiveEntry readZip(File zipFile, String fileName)

    throws IOException {

    ZipFile zf = new ZipFile(zipFile);

    Enumeration zips = zf.getEntries();

    ZipArchiveEntry zip = null;

    while (zips.hasMoreElements()) {

    zip = zips.nextElement();

    if (fileName.equals(zip.getName())) {

    return zip;

    }

    }

    return null;

    }

    開發者ID:hoozheng,項目名稱:AndroidRobot,代碼行數:14,

    示例17: findBestSource

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * Find best source.

    *

    * @param source the source

    * @param target the target

    * @param targetEntry the target entry

    * @return the zip archive entry

    * @throws IOException Signals that an I/O exception has occurred.

    */

    public ZipArchiveEntry findBestSource(ZipFile source, ZipFile target, ZipArchiveEntry targetEntry) throws IOException {

    ArrayList ret = new ArrayList<>();

    for (ZipArchiveEntry next : source.getEntries(targetEntry.getName())) {

    if (next.getCrc() == targetEntry.getCrc())

    return next;

    ret.add(next);

    }

    if (ret.size() == 0)

    return null;

    if (ret.size() == 1 || targetEntry.isDirectory())

    return ret.get(0);

    //More than one and no matching crc --- need to calculate xdeltas and pick the shortest

    ZipArchiveEntry retEntry = null;

    for (ZipArchiveEntry sourceEntry : ret) {

    try (ByteArrayOutputStream outbytes = new ByteArrayOutputStream()) {

    Delta d = new Delta();

    DiffWriter diffWriter = new GDiffWriter(new DataOutputStream(outbytes));

    int sourceSize = (int) sourceEntry.getSize();

    byte[] sourceBytes = new byte[sourceSize];

    try (InputStream sourceStream = source.getInputStream(sourceEntry)) {

    for (int erg = sourceStream.read(sourceBytes); erg < sourceBytes.length; erg += sourceStream.read(sourceBytes, erg, sourceBytes.length - erg));

    }

    d.compute(sourceBytes, target.getInputStream(targetEntry), diffWriter);

    byte[] nextDiff = outbytes.toByteArray();

    if (calculatedDelta == null || calculatedDelta.length > nextDiff.length) {

    retEntry = sourceEntry;

    calculatedDelta = nextDiff;

    }

    }

    }

    return retEntry;

    }

    開發者ID:NitorCreations,項目名稱:javaxdelta,代碼行數:42,

    示例18: getEntry

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * Gets the entry.

    *

    * @param source the source

    * @param name the name

    * @param crc the crc

    * @return the entry

    */

    private ZipArchiveEntry getEntry(ZipFile source, String name, long crc) {

    for (ZipArchiveEntry next : source.getEntries(name)) {

    if (next.getCrc() == crc)

    return next;

    }

    if (!JarDelta.zipFilesPattern.matcher(name).matches()) {

    return null;

    } else {

    return source.getEntry(name);

    }

    }

    開發者ID:NitorCreations,項目名稱:javaxdelta,代碼行數:20,

    示例19: getPatchEntry

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * Gets the patch entry.

    *

    * @param source the source

    * @param name the name

    * @param crc the crc

    * @return the patch entry

    */

    private ZipArchiveEntry getPatchEntry(ZipFile source, String name, long crc) {

    for (ZipArchiveEntry next : source.getEntries(name)) {

    long nextCrc = Long.parseLong(next.getComment());

    if (nextCrc == crc)

    return next;

    }

    return null;

    }

    開發者ID:NitorCreations,項目名稱:javaxdelta,代碼行數:17,

    示例20: parseMQZip

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * 解析 memoQ 的源文件,並將內容拷貝至骨架文件中

    * @param mqZip

    * @param hsSkeletonR8 hsxliff的骨架文件

    * @throws Exception

    */

    private void parseMQZip(String mqZip, String hsSkeleton) throws Exception{

    ZipFile zipFile = new ZipFile(new File(mqZip), "utf-8");

    Enumeration> e = zipFile.getEntries();

    byte ch[] = new byte[1024];

    String outputFile = "";

    File mqSklTempFile = File.createTempFile("tempskl", "skl");

    mqSklTempFile.deleteOnExit();

    while (e.hasMoreElements()) {

    ZipArchiveEntry zipEntry = (ZipArchiveEntry) e.nextElement();

    if ("document.mqxliff".equals(zipEntry.getName())) {

    outputFile = hsSkeleton;

    }else {

    outputFile = mqSklTempFile.getAbsolutePath();

    }

    File zfile = new File(outputFile);

    FileOutputStream fouts = new FileOutputStream(zfile);

    InputStream in = zipFile.getInputStream(zipEntry);

    int i;

    while ((i = in.read(ch)) != -1)

    fouts.write(ch, 0, i);

    fouts.close();

    in.close();

    }

    //解析r8骨加文件,並把 mq 的骨架信息添加到 r8 的骨架文件中

    parseHSSkeletonFile();

    copyMqSklToHsSkl(mqSklTempFile);

    }

    開發者ID:heartsome,項目名稱:translationstudio8,代碼行數:35,

    示例21: testZipFile

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @Test

    public void testZipFile() throws Exception {

    String aTargetFilename = "target/Z0-input.zip";

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();

    aTasklet.setSourceBaseDirectory(new FileSystemResource("src/test/resources/testFiles/"));

    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();

    aSourceFactory.setPattern("file:src/test/resources/testFiles/input.csv");

    aTasklet.setSourceFactory(aSourceFactory );

    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();

    aDestinationFactory.setExpression(aTargetFilename);

    aTasklet.setDestinationFactory(aDestinationFactory );

    assertFalse(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);

    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));

    verify(aStepContribution, times(1)).incrementReadCount();

    verify(aStepContribution, times(1)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());

    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));

    Enumeration aEntries = aZipFile.getEntries();

    assertTrue(aEntries.hasMoreElements());

    assertEquals("input.csv", aEntries.nextElement().getName());

    assertFalse(aEntries.hasMoreElements());

    aZipFile.close();

    }

    開發者ID:acxio,項目名稱:AGIA,代碼行數:28,

    示例22: testZipTwoFile

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @Test

    public void testZipTwoFile() throws Exception {

    FileUtils.forceMkdir(new File("target/Z-testfiles/source"));

    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/CP0-input.csv"));

    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/CP1-input.csv"));

    String aTargetFilename = "target/Z1-input.zip";

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();

    aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/source/"));

    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();

    aSourceFactory.setPattern("file:target/Z-testfiles/source/*input*.csv");

    aTasklet.setSourceFactory(aSourceFactory );

    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();

    aDestinationFactory.setExpression(aTargetFilename);

    aTasklet.setDestinationFactory(aDestinationFactory );

    assertFalse(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);

    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));

    verify(aStepContribution, times(2)).incrementReadCount();

    verify(aStepContribution, times(2)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());

    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));

    Enumeration aEntries = aZipFile.getEntries();

    assertTrue(aEntries.hasMoreElements());

    assertEquals("CP0-input.csv", aEntries.nextElement().getName());

    assertTrue(aEntries.hasMoreElements());

    assertEquals("CP1-input.csv", aEntries.nextElement().getName());

    assertFalse(aEntries.hasMoreElements());

    aZipFile.close();

    }

    開發者ID:acxio,項目名稱:AGIA,代碼行數:34,

    示例23: testZipDirectory

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @Test

    public void testZipDirectory() throws Exception {

    FileUtils.forceMkdir(new File("target/Z-testfiles/source"));

    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/CP0-input.csv"));

    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/CP1-input.csv"));

    String aTargetFilename = "target/Z2-input.zip";

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();

    aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/"));

    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();

    aSourceFactory.setPattern("file:target/Z-testfiles/source/");

    aTasklet.setSourceFactory(aSourceFactory );

    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();

    aDestinationFactory.setExpression(aTargetFilename);

    aTasklet.setDestinationFactory(aDestinationFactory );

    assertFalse(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);

    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));

    verify(aStepContribution, times(3)).incrementReadCount();

    verify(aStepContribution, times(3)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());

    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));

    Enumeration aEntries = aZipFile.getEntries();

    assertTrue(aEntries.hasMoreElements());

    assertEquals("source", aEntries.nextElement().getName());

    assertTrue(aEntries.hasMoreElements());

    assertEquals("source/CP0-input.csv", aEntries.nextElement().getName());

    assertTrue(aEntries.hasMoreElements());

    assertEquals("source/CP1-input.csv", aEntries.nextElement().getName());

    assertFalse(aEntries.hasMoreElements());

    aZipFile.close();

    }

    開發者ID:acxio,項目名稱:AGIA,代碼行數:36,

    示例24: testZipDirectories

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @Test

    public void testZipDirectories() throws Exception {

    FileUtils.forceMkdir(new File("target/Z-testfiles/source/subdir"));

    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/CP0-input.csv"));

    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/subdir/CP1-input.csv"));

    String aTargetFilename = "target/Z3-input.zip";

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();

    aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/"));

    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();

    aSourceFactory.setPattern("file:target/Z-testfiles/source/");

    aTasklet.setSourceFactory(aSourceFactory );

    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();

    aDestinationFactory.setExpression(aTargetFilename);

    aTasklet.setDestinationFactory(aDestinationFactory );

    assertFalse(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);

    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));

    verify(aStepContribution, times(4)).incrementReadCount();

    verify(aStepContribution, times(4)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());

    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));

    Enumeration aEntries = aZipFile.getEntries();

    assertTrue(aEntries.hasMoreElements());

    assertEquals("source", aEntries.nextElement().getName());

    assertTrue(aEntries.hasMoreElements());

    assertEquals("source/CP0-input.csv", aEntries.nextElement().getName());

    assertTrue(aEntries.hasMoreElements());

    assertEquals("source/subdir", aEntries.nextElement().getName());

    assertTrue(aEntries.hasMoreElements());

    assertEquals("source/subdir/CP1-input.csv", aEntries.nextElement().getName());

    assertFalse(aEntries.hasMoreElements());

    aZipFile.close();

    }

    開發者ID:acxio,項目名稱:AGIA,代碼行數:38,

    示例25: testZipDirectoriesNotRecursive

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @Test

    public void testZipDirectoriesNotRecursive() throws Exception {

    FileUtils.forceMkdir(new File("target/Z-testfiles/source/subdir"));

    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/CP0-input.csv"));

    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/subdir/CP1-input.csv"));

    String aTargetFilename = "target/Z4-input.zip";

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();

    aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/"));

    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();

    aSourceFactory.setPattern("file:target/Z-testfiles/source/");

    aTasklet.setSourceFactory(aSourceFactory );

    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();

    aDestinationFactory.setExpression(aTargetFilename);

    aTasklet.setDestinationFactory(aDestinationFactory );

    aTasklet.setRecursive(false);

    assertFalse(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);

    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));

    verify(aStepContribution, times(2)).incrementReadCount();

    verify(aStepContribution, times(2)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());

    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));

    Enumeration aEntries = aZipFile.getEntries();

    assertTrue(aEntries.hasMoreElements());

    assertEquals("source", aEntries.nextElement().getName());

    assertTrue(aEntries.hasMoreElements());

    assertEquals("source/CP0-input.csv", aEntries.nextElement().getName());

    assertFalse(aEntries.hasMoreElements());

    aZipFile.close();

    }

    開發者ID:acxio,項目名稱:AGIA,代碼行數:35,

    示例26: testExistingZipFile

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @Test

    public void testExistingZipFile() throws Exception {

    File aTargetFile = File.createTempFile("target/Z8-input", ".zip");

    String aTargetFilename = aTargetFile.getAbsolutePath();

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();

    aTasklet.setSourceBaseDirectory(new FileSystemResource("src/test/resources/testFiles/"));

    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();

    aSourceFactory.setPattern("file:src/test/resources/testFiles/input.csv");

    aTasklet.setSourceFactory(aSourceFactory );

    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();

    aDestinationFactory.setExpression(aTargetFilename);

    aTasklet.setDestinationFactory(aDestinationFactory );

    assertTrue(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);

    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));

    verify(aStepContribution, times(1)).incrementReadCount();

    verify(aStepContribution, times(1)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());

    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));

    Enumeration aEntries = aZipFile.getEntries();

    assertTrue(aEntries.hasMoreElements());

    assertEquals("input.csv", aEntries.nextElement().getName());

    assertFalse(aEntries.hasMoreElements());

    aZipFile.close();

    }

    開發者ID:acxio,項目名稱:AGIA,代碼行數:30,

    示例27: testExistingLockedZipFile

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @Test

    public void testExistingLockedZipFile() throws Exception {

    exception.expect(IOException.class);

    File aTargetFile = File.createTempFile("target/Z9-input", ".zip");

    aTargetFile.setWritable(false);

    String aTargetFilename = aTargetFile.getAbsolutePath();

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();

    aTasklet.setSourceBaseDirectory(new FileSystemResource("src/test/resources/testFiles/"));

    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();

    aSourceFactory.setPattern("file:src/test/resources/testFiles/input.csv");

    aTasklet.setSourceFactory(aSourceFactory );

    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();

    aDestinationFactory.setExpression(aTargetFilename);

    aTasklet.setDestinationFactory(aDestinationFactory );

    assertTrue(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);

    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));

    verify(aStepContribution, times(1)).incrementReadCount();

    verify(aStepContribution, times(1)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());

    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));

    Enumeration aEntries = aZipFile.getEntries();

    assertTrue(aEntries.hasMoreElements());

    assertEquals("input.csv", aEntries.nextElement().getName());

    assertFalse(aEntries.hasMoreElements());

    aZipFile.close();

    }

    開發者ID:acxio,項目名稱:AGIA,代碼行數:32,

    示例28: extractZip

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    /**

    * Extracts a {@code *.zip} archive into the target folder.

    * @param monitor the progress monitor

    * @param archiveFile the archive file

    * @param targetDirectory the target folder

    * @throws IOException if failed to extract the archive

    */

    public static void extractZip(

    IProgressMonitor monitor,

    File archiveFile,

    File targetDirectory) throws IOException {

    SubMonitor sub = SubMonitor.convert(monitor, Messages.IoUtils_monitorExtractZip, 10);

    try {

    ZipFile zip = new ZipFile(archiveFile);

    try {

    Enumeration entries = zip.getEntries();

    while (entries.hasMoreElements()) {

    ZipArchiveEntry entry = entries.nextElement();

    if (entry.isDirectory()) {

    createDirectory(targetDirectory, entry);

    } else {

    InputStream input = zip.getInputStream(entry);

    try {

    File file = createFile(targetDirectory, entry, input);

    setFileMode(file, entry.getUnixMode());

    } finally {

    input.close();

    }

    sub.worked(1);

    sub.setWorkRemaining(10);

    }

    }

    } finally {

    zip.close();

    }

    } finally {

    if (monitor != null) {

    monitor.done();

    }

    }

    }

    開發者ID:asakusafw,項目名稱:asakusafw-shafu,代碼行數:42,

    示例29: testExportArchiveZip

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    @Test

    public void testExportArchiveZip() throws Exception {

    final Project p = makeGoodProject();

    final List infos = this.bean.getAvailablePackagingInfos(p);

    final PackagingInfo zipPi = Iterables.find(infos, new Predicate() {

    @Override

    public boolean apply(PackagingInfo t) {

    return t.getMethod() == PackagingInfo.PackagingMethod.ZIP;

    }

    });

    final File f = File.createTempFile("test", zipPi.getName());

    final FileOutputStream fos = new FileOutputStream(f);

    this.bean.export(p, "http://example.com/my_experiemnt", PackagingInfo.PackagingMethod.ZIP, fos);

    fos.close();

    final ZipFile zf = new ZipFile(f);

    final Enumeration en = zf.getEntries();

    final Set entries = new HashSet();

    entries.addAll(java.util.Arrays.asList("test-exp-id.soft.txt", "raw_file.data", "derived_file.data",

    "supplimental.data"));

    while (en.hasMoreElements()) {

    final ZipArchiveEntry ze = en.nextElement();

    assertTrue(ze.getName() + " unexpected", entries.remove(ze.getName()));

    }

    assertTrue(entries.toString() + " not found", entries.isEmpty());

    }

    開發者ID:NCIP,項目名稱:caarray,代碼行數:28,

    示例30: init

    ​點讚 2

    import org.apache.commons.compress.archivers.zip.ZipFile; //導入方法依賴的package包/類

    private void init()

    throws MalformedURLException,

    IOException {

    if (!wrs2Shape.exists()) {

    if (!wrs2Directory.delete()) {

    LOGGER.warn("Unable to delete '" + wrs2Directory.getAbsolutePath() + "'");

    }

    final File wsDir = wrs2Directory.getParentFile();

    if (!wsDir.exists() && !wsDir.mkdirs()) {

    LOGGER.warn("Unable to create directory '" + wsDir.getAbsolutePath() + "'");

    }

    // download and unzip the shapefile

    final File targetFile = new File(

    wsDir,

    WRS2_SHAPE_ZIP);

    if (targetFile.exists()) {

    if (!targetFile.delete()) {

    LOGGER.warn("Unable to delete file '" + targetFile.getAbsolutePath() + "'");

    }

    }

    FileUtils.copyURLToFile(

    new URL(

    WRS2_SHAPE_URL),

    targetFile);

    final ZipFile zipFile = new ZipFile(

    targetFile);

    try {

    final Enumeration entries = zipFile.getEntries();

    while (entries.hasMoreElements()) {

    final ZipArchiveEntry entry = entries.nextElement();

    if (!entry.isDirectory()) {

    FileUtils.copyInputStreamToFile(

    zipFile.getInputStream(entry),

    new File(

    wsDir,

    entry.getName()));

    // HP Fortify "Path Traversal" false positive

    // What Fortify considers "user input" comes only

    // from users with OS-level access anyway

    }

    }

    }

    finally {

    zipFile.close();

    }

    }

    // read the shapefile and cache the features for quick lookup by path

    // and row

    try {

    final Map map = new HashMap();

    map.put(

    "url",

    wrs2Shape.toURI().toURL());

    final DataStore dataStore = DataStoreFinder.getDataStore(map);

    if (dataStore == null) {

    LOGGER.error("Unable to get a datastore instance, getDataStore returned null");

    return;

    }

    final SimpleFeatureSource source = dataStore.getFeatureSource(WRS2_TYPE_NAME);

    final SimpleFeatureCollection featureCollection = source.getFeatures();

    wrs2Type = featureCollection.getSchema();

    final SimpleFeatureIterator iterator = featureCollection.features();

    while (iterator.hasNext()) {

    final SimpleFeature feature = iterator.next();

    final Number path = (Number) feature.getAttribute("PATH");

    final Number row = (Number) feature.getAttribute("ROW");

    featureCache.put(

    new WRS2Key(

    path.intValue(),

    row.intValue()),

    (MultiPolygon) feature.getDefaultGeometry());

    }

    }

    catch (final IOException e) {

    LOGGER.error(

    "Unable to read wrs2_asc_desc shapefile '" + wrs2Shape.getAbsolutePath() + "'",

    e);

    throw (e);

    }

    }

    開發者ID:locationtech,項目名稱:geowave,代碼行數:82,

    注:本文中的org.apache.commons.compress.archivers.zip.ZipFile.getEntries方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。

    展开全文
    weixin_39623271 2021-02-28 12:18:00
  • 一、zipfile模块的简述zipfile是python里用来做zip格式编码的压缩和解压缩的,由于是很常见的zip格式,所以这个模块使用频率也是比较高的,在这里对zipfile的使用方法做一些记录。即方便自己也方便别人。zipfile里有...

    一、zipfile模块的简述

    zipfile是python里用来做zip格式编码的压缩和解压缩的,由于是很常见的zip格式,所以这个模块使用频率也是比较高的,

    在这里对zipfile的使用方法做一些记录。即方便自己也方便别人。

    zipfile里有两个非常常用的class, 分别是ZipFile和ZipInfo, 在绝大多数的情况下,我们只需要使用这两个class就可以了。

    ZipFile是主要的类,用来创建和读取zip文件而ZipInfo是存储的zip文件的每个文件的信息的。

    下面我们就来介绍这两个类的基本操作:

    二、ZipFile和Zipinfo这两个类的基本操作

    1、class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])

    创建一个ZipFile对象,表示一个zip文件。参数file表示文件的路径或类文件对象(file-like object);参数mode指示打开zip文件的模式,

    默认值为'r',表示读已经存在的zip文件,也可以为'w'或'a','w'表示新建一个zip文档或覆盖一个已经存在的zip文档,

    import zipfile

    f = zipfile.ZipFile(filename, 'r') # 这里的第二个参数用r表示是读取zip文件,w或a是创建一个zip文件

    for f_name in f.namelist(): #z.namelist() 会返回压缩包内所有文件名的列表。

    print(f_name)

    #上面的代码是读取一个zip压缩包里所有文件的名字。

    'a'表示将数据附加到一个现存的zip文档中。参数compression表示在写zip文档时使用的压缩方法,它的值可以是zipfile. ZIP_STORED 或zipfile. ZIP_DEFLATED。如果要操作的zip文件大小超过2G,应该将allowZip64设置为True。

    ZipFile还提供了如下常用的方法和属性:

    ZipFile.getinfo(name)

    获取zip文档内指定文件的信息。返回一个zipfile.ZipInfo对象,它包括文件的详细信息。

    ZipFile.infolist()

    获取zip文档内所有文件的信息,返回一个zipfile.ZipInfo的列表。

    ZipFile.namelist()

    获取zip文档内所有文件的名称列表。

    ZipFile.extract(member[, path[, pwd]])

    将zip文档内的指定文件解压到当前目录。参数member指定要解压的文件名称或对应的ZipInfo对象;参数path指定了解析文件保存的文件夹;

    参数pwd为解压密码。下面一个例子将保存在程序根目录下的duoduo.zip内的所有文件解压到D:/Work目录:

    import zipfile, os

    f = zipfile.ZipFile(os.path.join(os.getcwd(), 'duoduo.zip')) #拼接成一个路径

    for file in f.namelist():

    f.extract(file, r'd:/Work') #在d:/Work中解压文件

    f.close()

    2a8741e9e0b0d482c662f19f4507d4d3.png

    上面是os.getcwd的用法!!

    ZipFile.extractall([path[, members[, pwd]]])

    解压zip文档中的所有文件到当前目录。参数members的默认值为zip文档内的所有文件名称列表,也可以自己设置,选择要解压的文件名称。

    ZipFile.printdir()

    将zip文档内的信息打印到控制台上。

    ZipFile.setpassword(pwd)

    设置zip文档的密码。

    ZipFile.read(name[, pwd])

    获取zip文档内指定文件的二进制数据。下面的例子演示了read()的使用,zip文档内包括一个duoduo.txt的文本文件,使用read()方法读取其二进制数据,然后保存到D:/duoduo.txt。

    import zipfile, os

    zipFile = zipfile.ZipFile(os.path.join(os.getcwd(), 'duoduo.zip'))

    data = zipFile.read('duoduo.txt')

    # (lambda f, d: (f.write(d), f.close()))(open(r'd:/duoduo.txt', 'wb'), data) #一行语句就完成了写文件操作。仔细琢磨哦~_~

    with open(r'd:/duoduo.txt','wb') as f:

    for d in data:

    f.write(d)

    zipFile.close()

    ZipFile.write(filename[, arcname[, compress_type]])

    将指定文件添加到zip文档中。filename为文件路径,arcname为添加到zip文档之后保存的名称, 参数compress_type表示压缩方法,它的值可以是zipfile. ZIP_STORED 或zipfile. ZIP_DEFLATED。下面的例子演示了如何创建一个zip文档,并将文件D:/test.doc添加到压缩文档中。

    import zipfile, os

    zipFile = zipfile.ZipFile(r'D:/test.zip'), 'w')

    zipFile.write(r'D:/test.doc', '保存的名字', zipfile.ZIP_DEFLATED)

    zipFile.close()

    ZipFile.writestr(zinfo_or_arcname, bytes)

    writestr()支持将二进制数据直接写入到压缩文档。

    2、Class ZipInfo

    ZipFile.getinfo(name) 方法返回的是一个ZipInfo对象,表示zip文档中相应文件的信息。它支持如下属性:

    ZipInfo.filename: 获取文件名称。

    ZipInfo.date_time: 获取文件最后修改时间。返回一个包含6个元素的元组:(年, 月, 日, 时, 分, 秒)

    ZipInfo.compress_type: 压缩类型。

    ZipInfo.comment: 文档说明。

    ZipInfo.extr: 扩展项数据。

    ZipInfo.create_system: 获取创建该zip文档的系统。

    ZipInfo.create_version: 获取 创建zip文档的PKZIP版本。

    ZipInfo.extract_version: 获取 解压zip文档所需的PKZIP版本。

    ZipInfo.reserved: 预留字段,当前实现总是返回0。

    ZipInfo.flag_bits: zip标志位。

    ZipInfo.volume: 文件头的卷标。

    ZipInfo.internal_attr: 内部属性。

    ZipInfo.external_attr: 外部属性。

    ZipInfo.header_offset: 文件头偏移位。

    ZipInfo.CRC: 未压缩文件的CRC-32。

    ZipInfo.compress_size: 获取压缩后的大小。

    ZipInfo.file_size: 获取未压缩的文件大小。

    下面一个简单的例子说明这些属性的意思:

    import zipfile, os

    zipFile = zipfile.ZipFile(os.path.join(os.getcwd(), 'duoduo.zip'))

    zipInfo = zipFile.getinfo('文件中的文件.txt')

    print ('filename:', zipInfo.filename) #获取文件名称

    print ('date_time:', zipInfo.date_time) #获取文件最后修改时间。返回一个包含6个元素的元组:(年, 月, 日, 时, 分, 秒)

    print ('compress_type:', zipInfo.compress_type) #压缩类型

    print ('comment:', zipInfo.comment) #文档说明

    print ('extra:', zipInfo.extra) #扩展项数据

    print ('create_system:', zipInfo.create_system) #获取创建该zip文档的系统。

    print ('create_version:', zipInfo.create_version) #获取 创建zip文档的PKZIP版本。

    print ('extract_version:', zipInfo.extract_version) #获取 解压zip文档所需的PKZIP版本。

    print ('extract_version:', zipInfo.reserved) # 预留字段,当前实现总是返回0。

    print ('flag_bits:', zipInfo.flag_bits) #zip标志位。

    print ('volume:', zipInfo.volume) # 文件头的卷标。

    print ('internal_attr:', zipInfo.internal_attr) #内部属性。

    print ('external_attr:', zipInfo.external_attr) #外部属性。

    print ('header_offset:', zipInfo.header_offset) # 文件头偏移位。

    print ('CRC:', zipInfo.CRC) # 未压缩文件的CRC-32。

    print ('compress_size:', zipInfo.compress_size) #获取压缩后的大小。

    print ('file_size:', zipInfo.file_size) #获取未压缩的文件大小。

    zipFile.close() #

    如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

    展开全文
    weixin_26774169 2021-01-29 04:45:37
  • 我有一个zip文件,其中可以包含任意数量的zipfile(也是递归的).我需要遍历所有这些.现在,我有一个函数将zipInputStream和zipFile作为参数.问题是;如果我在另一个zip内找到一个zip,则我再次递归调用此函数.所以我不...

    我有一个zip文件,其中可以包含任意数量的zipfile(也是递归的).我需要遍历所有这些.

    现在,我有一个函数将zipInputStream和zipFile作为参数.问题是;如果我在另一个zip内找到一个zip,则我再次递归调用此函数.所以我不知道如何在另一个zipfile中为zipfile创建zipFile对象.有人可以建议一种方法吗?你以前遇到过这个吗?

    该代码段将如下所示.

    private void checkZIP(ZipInputStream zInpStream, ZipFile zf) {

    try {

    ZipEntry zipEntry = zInpStream.getNextEntry();

    while (zipEntry != null) {

    String entryName = zipEntry.getName();

    if(entryName.endsWith(".zip"))

    checkZIP(new ZipInputStream(zf.getInputStream(zipEntry)),);

    //other files parsing apart from zip.

    zInpStream.closeEntry();

    zipEntry = zInpStream.getNextEntry();

    }

    zInpStream.close();

    } catch(Exception ioe) {

    //catching specific exceptions here. But did not want to put al

    }

    }

    编辑:因为我需要该zip文件对象.如果遇到XML文件,则需要创建一个Document对象.因此,如果我在DocumentBuilder中为parse()方法传递了常规的zipInputStream,它将关闭流,而我将无法再次使用它.所以我在DocumentBuilder parse()中使用了(ZipFile对象).getInputStream(currentEntryForXML).

    展开全文
    weixin_42510012 2021-02-12 16:57:53
  • 我想从zip文件中删除文件的唯一方法是创建一个临时zipfile,而不删除该文件,然后将其重命名为原始文件名。在python 2.4中,ZipInfo类具有属性file_offset,因此可以创建第二个zip文件并将数据复制到其他文件而无需...

    我想从zip文件中删除文件的唯一方法是创建一个临时zipfile,而不删除该文件,然后将其重命名为原始文件名。

    在python 2.4中,ZipInfo类具有属性file_offset,因此可以创建第二个zip文件并将数据复制到其他文件而无需解压缩/重新压缩。

    python 2.6中缺少此file_offset,是否还有其他选择,而不是通过解压缩每个文件然后再次重新压缩来创建另一个zipfile?

    我搜索并没有找到任何内容,也许有直接删除zip文件中文件的直接方法。

    我在Python Bug Tracker上发现了该线程,讨论了从zip文件中删除文件的困难:bugs.python.org/issue6818

    以下代码段对我有用(从Zip存档中删除所有* .exe文件):

    zin = zipfile.ZipFile ('archive.zip', 'r')

    zout = zipfile.ZipFile ('archve_new.zip', 'w')

    for item in zin.infolist():

    buffer = zin.read(item.filename)

    if (item.filename[-4:] != '.exe'):

    zout.writestr(item, buffer)

    zout.close()

    zin.close()

    如果您将所有内容都读到内存中,则可以省去第二个文件。但是,此片段重新压缩了所有内容。

    仔细检查后,ZipInfo.header_offset是文件开始的偏移量。该名称具有误导性,但主要的Zip标头实际上存储在文件末尾。我的十六进制编辑器确认了这一点。

    因此,您将遇到以下问题:您还需要删除主标头中的目录条目,否则它将指向一个不再存在的文件。如果您也要保留要删除的文件的本地标头,则可以保留主标头的完整性,但是我不您是如何使用旧模块执行此操作的?

    如果不修改主标头,则在打开它时会出现错误" zipfile中缺少X字节"。这可能有助于您了解如何修改主标头。

    谢谢,但是如果我没记错的话-当您查看zipfile.writestr时,您会看到这只是重新压缩。仅复制已经压缩的文件而不取消压缩,然后再次压缩它们会更快。

    @RSabt我同意mdm的观点,即到目前为止,唯一可行的选择是解压缩和重新压缩。顺便说一句,我想指出mdm的代码会有所帮助,但是当您要更认真地进行操作时,最好使用os.path.splitext()。

    变量名称+1为zin zout = D

    不幸的是笨拙,但它可以工作:)谢谢!

    您也可以避免提取可执行文件。首先检查名称,如果不是可执行文件,则检查输入。将节省一些无用的提取时间。

    不是很优雅,但这是我做到的:

    import subprocess

    import zipfile

    z = zipfile.ZipFile(zip_filename)

    files_to_del = filter( lambda f: f.endswith('exe'), z.namelist()]

    cmd=['zip', '-d', zip_filename] + files_to_del

    subprocess.check_call(cmd)

    # reload the modified archive

    z = zipfile.ZipFile(zip_filename)

    这就是我最终要做的。难看,但是ZipFile似乎没有删除或更新/替换文件的方法。

    ruamel.std.zipfile 1中的例程delete_from_zip_file允许您基于ZIP中的完整路径或基于(re)模式删除文件。例如。您可以使用以下命令从test.zip中删除所有.exe文件

    from ruamel.std.zipfile import delete_from_zip_file

    delete_from_zip_file('test.zip', pattern='.*.exe')

    (请注意*之前的点)。

    这与mdm的解决方案(包括需要重新压缩)相似,但是会在内存中重新创建ZIP文件(使用类InMemZipFile()),并在完全读取后覆盖旧文件。

    1 免责声明:我是该软件包的作者。 sub>

    delete_from_zip_file例程对我来说非常有用,但是在尝试从具有一组文件夹的大型归档文件(大小约为3Gb)中删除许多文件时收到此错误:" LargeZipFile:Zipfile大小将需要ZIP64扩展名"。我猜应该在ruamel.std.zipfile中的init.py文件中进行修改(例如,对于zipfile.ZipFile(..),allowZip64 = True),对吗?

    我从没与allowZip64一起工作过,不知道它的含义。

    展开全文
    weixin_36350504 2021-04-26 18:42:41
  • weixin_42373893 2021-01-14 09:40:36
  • weixin_42507868 2021-01-14 09:39:22
  • weixin_36219745 2021-01-28 19:44:39
  • weixin_42402188 2021-02-11 03:32:40
  • xietansheng 2021-04-09 19:14:02
  • weixin_35064481 2021-01-14 14:59:10
  • weixin_33814002 2021-02-26 16:50:15
  • weixin_34515820 2021-02-03 10:14:18
  • weixin_39723920 2021-01-14 09:40:39
  • weixin_39609541 2021-03-17 17:21:11
  • weixin_33181210 2021-01-14 09:40:28
  • lpwmm 2021-11-06 16:40:19
  • Likianta 2021-09-13 03:02:40
  • weixin_42629671 2021-03-05 14:03:31
  • weixin_30127493 2021-01-14 09:40:37
  • m0_51004308 2021-04-10 16:50:23
  • goodgoodstudy___ 2021-11-16 14:54:28
  • weixin_31510897 2021-02-04 07:35:55
  • weixin_39834475 2021-03-09 04:56:02
  • weixin_39618456 2021-01-14 09:39:23
  • qq_35260390 2021-03-21 17:18:41
  • weixin_39615956 2021-02-28 15:58:22
  • y_bccl27 2021-11-22 12:47:17
  • weixin_39952937 2021-04-26 19:56:34
  • weixin_39521068 2021-01-14 09:40:36

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 30,873
精华内容 12,349
关键字:

zipfile