search
HomeBackend DevelopmentPHP TutorialAtitit. 解压缩zip文件 的实现最佳实践 java c# .net php

Atitit. 解压缩zip文件 的实现最佳实践 java c# .net php  

 

 

 

1. Jdk zip 跟apache ant zip 1

2. Apache Ant包进行ZIP文件压缩,upzip 大概流程.. 1

3. 读文件名称ok,但是cant读取到input说NPE.. 2

4. Ant1.8.2.jar 2

5. #---详细code 2

6. 参考 4

 

1.   Jdk zip 跟apache ant zip

 

下面实现的功能是zip文件中的图像文件解压到当前目录下,用jdk自带的处理zip文件的代码处理的,但是不能处理中文名称的文件,要不然就会出错。

 

下面是用的apache的zip文件处理包进行处理的,可以处理中文名称的文件,功能跟上面的一样。

使用apache ant version1.7的tools.zip来解压zip文件,解决中文问题

1.7 blow的好像还是不支持中文..

作者:: 老哇的爪子 Attilax 艾龙,  EMAIL:1466519819@qq.com

 

2. Apache Ant包进行ZIP文件压缩,upzip 大概流程..

许多年前就遇到过这种业务,对ZIP标准压缩文件解压。之前写的操作类现在找不到了,最近项目中又要处理这种业务,所以重新写了一个。Java提供 了处理ZIP包的API。但是对中文支持不是很好,所以我直接用Apache Ant里的ZIP操作API来进行处理。ANT的API解决了中文支持问题,而且用起来也非常方便。以下是操作类。

以下的类只是用到Apache的一小部分功能。具体更多的API,请参考文档。在此不多说明了。

* 在项目中导入Apache的ant.jar包到Lib中

 

 

 

3. 读文件名称ok,但是cant读取到input说NPE..

 

Cause:::encode问题.. 默认好像是utf8..but 实际是gbk... 

org.apache.tools.zip.ZipFile zipFile =new ZipFile(zipFileName, "gbk");

 

二、在unZipFiles方法中直接使用ZipFile zip = new ZipFile(zipFile); 解压缩时发现中文仍然乱码,改成ZipFile zip = new ZipFile(zipFile,“GBK”); 后中文正常了,可能和项目具体配置与运行环境有关吧。

 

4. Ant1.8.2.jar

 

5. #---详细code

/**

 * 解压静态方法

 * @param zipFileName

 * @param outputDirectory

 * @throws Exception

 */

public static void extract(String zipFileName,String outputDirectory,String encode) throws Exception{

try {

// = "utf-8";

org.apache.tools.zip.ZipFile zipFile =new ZipFile(zipFileName, encode);

//new org.apache.tools.zip.ZipFile(zipFileName);

java.util.Enumeration e = zipFile.getEntries();

 

org.apache.tools.zip.ZipEntry zipEntry = null;

 

while (e.hasMoreElements()){

zipEntry = (ZipEntry)e.nextElement();

 System.out.println("unziping "+zipEntry.getName());

 try {

 upzip(outputDirectory, zipFile, zipEntry);

} catch (zipEntryIsNullEx e2) {

 System.out.println(e2.getMessage());

 System.out.println("------------");

}

}

}

catch (Exception ex){

System.out.println("解压文件异常"+ex.getMessage());

ex.printStackTrace();

}

}

private static void upzip(String outputDirectory, org.apache.tools.zip.ZipFile zipFile, org.apache.tools.zip.ZipEntry zipEntry) throws  IOException, ZipException, FileNotFoundException, zipEntryIsNullEx {

if (zipEntry.isDirectory()){

String name=zipEntry.getName();

name=name.substring(0,name.length()-1);// for del fesyegeor

mkDirs(outputDirectory+File.separator+name);

//System.out.println("创建目录:"+outputDirectory+File.separator+name);

 

}else{  //file entry o9o

String name=zipEntry.getName();

String dir = name.substring(0,name.lastIndexOf("/"));

mkDirs(outputDirectory+File.separator+dir);

//System.out.println("创建文件:"+outputDirectory+File.separator+name);

File f=new File(outputDirectory+File.separator+zipEntry.getName());

f.createNewFile();

InputStream in = zipFile.getInputStream(zipEntry);

if(in==null)

throw new zipEntryIsNullEx("zipEntryIsNullEx:"+name);

FileOutputStream out=new FileOutputStream(f);

int c;

byte[] by=new byte[1024];

while((c=in.read(by)) != -1){

out.write(by,0,c);

}

out.close();

in.close();

}

}

 

6. 参考

 

Apache Ant包进行ZIP文件压缩 - 抹去浮华,沉淀深度 - ITeye技术网站.htm

基于apache zip包的压缩和解压缩程序_Crusoe_新浪博客

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools