/**
*
*/
package
com.yfei.uti.zip;
import
java.io.BufferedInputStream;
import
java.io.BufferedOutputStream;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileOutputStream;
import
java.util.Enumeration;
import
org.apache.tools.zip.ZipEntry;
import
org.apache.tools.zip.ZipFile;
import
org.apache.tools.zip.ZipOutputStream;
/**
* @author yangfei
* @since 2013-1-27
*/
public
class
ZipUtilApache {
static
final
int
BUFFER =
1024
;
public
static
void
zip(String destDirPath, String inputPath)
throws
Exception {
File inputFile =
new
File(inputPath);
File destDir =
new
File(destDirPath);
if
(!destDir.exists()) {
destDir.mkdir();
}
File destFile =
new
File(destDir + File.separator + inputFile.getName()
+
".zip"
);
ZipOutputStream out =
new
ZipOutputStream(
new
FileOutputStream(destFile));
out.setEncoding(
"GBK"
);
zip(out, inputFile,
""
);
System.out.println(
"zip done"
);
out.close();
}
private
static
void
zip(ZipOutputStream out, File f, String base)
throws
Exception {
System.out.println(
"Zipping "
+ f.getName());
if
(f.isDirectory()) {
File[] fl = f.listFiles();
if
(base.length() >
0
) {
out.putNextEntry(
new
ZipEntry(base +
"/"
));
}
base = base.length() ==
0
?
""
: base +
"/"
;
for
(
int
i =
0
; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
}
else
{
out.putNextEntry(
new
ZipEntry(base));
FileInputStream in =
new
FileInputStream(f);
int
len;
byte
[] buf =
new
byte
[BUFFER];
while
((len = in.read(buf,
0
, BUFFER)) != -
1
) {
out.write(buf,
0
, len);
}
in.close();
out.closeEntry();
}
}
/**
* 解压缩zip文件
*
* @param fileName
* 要解压的文件名 包含路径 如:"c:\\test.zip"
* @param filePath
* 解压后存放文件的路径 如:"c:\\temp"
* @throws Exception
*/
public
static
void
unZip(String fileName, String destFilePath)
throws
Exception {
ZipFile zipFile =
new
ZipFile(fileName,
"GBK"
);
Enumeration emu = zipFile.getEntries();
while
(emu.hasMoreElements()) {
ZipEntry entry = (ZipEntry) emu.nextElement();
if
(entry.isDirectory()) {
File dir =
new
File(destFilePath + entry.getName());
if
(!dir.exists()) {
dir.mkdirs();
}
continue
;
}
BufferedInputStream bis =
new
BufferedInputStream(zipFile
.getInputStream(entry));
File file =
new
File(destFilePath + entry.getName());
File parent = file.getParentFile();
if
(parent !=
null
&& (!parent.exists())) {
parent.mkdirs();
}
FileOutputStream fos =
new
FileOutputStream(file);
BufferedOutputStream bos =
new
BufferedOutputStream(fos, BUFFER);
byte
[] buf =
new
byte
[BUFFER];
int
len =
0
;
while
((len = bis.read(buf,
0
, BUFFER)) != -
1
) {
fos.write(buf,
0
, len);
}
bos.flush();
bos.close();
bis.close();
System.out.println(
"解压文件:"
+ file.getName());
}
zipFile.close();
}
}