apache ant下載地址:
http://ant.apache.org/bindownload.cgi
把lib/ant.jar放到我們項目的構建路徑中,只需要ant.jar。其實ant的zip API與jdk的高度相似,如果之前是用jdk的api寫的,基本上只要更改頂部的import包就可以了
| 代碼如下 |
複製代碼 |
|
package common;
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 java.util.List;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
public class ZipUtils {
public static void main(String[] args) throws Exception {
unzipPSD("/media/share/material/file/temp/1eeb28ecb8e0d6f2.zip","/media/share/material/file/temp/");
}
/**
* 解壓zip,
*
* @param zipFile 裡面可以有多個psd檔案,支援多級目錄
* @param targetPath 儲存目錄
* @throws Exception
*/
public static void unzipPSD(String zipPath, String targetPath) throws Exception {
ZipFile zipFile = new ZipFile(zipPath);
Enumeration emu = zipFile.getEntries();
int i = 0;
while (emu.hasMoreElements()) {
ZipEntry entry = (ZipEntry) emu.nextElement();
String fileName=entry.getName().toLowerCase();
if(!fileName.startsWith("__macosx/")&&fileName.endsWith("psd"))
{
//如果檔案名稱沒有以__macosx/開頭,且以psd結尾,就是psd檔案,解壓,在mac下壓縮的檔案,會自動加上__macosx目錄,但其實是沒用的
BufferedInputStream bis = new BufferedInputStream(
zipFile.getInputStream(entry));
File file = new File(targetPath + System.currentTimeMillis()+".psd");
//一次讀40K
int BUFFER=40960;
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
bos.close();
bis.close();
}
}
zipFile.close();
}
/**
* 壓縮多個檔案
* @param zipPath
* @param filePaths
*/
public static void zipFiles(String zipPath,List filePaths)
{
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(zipPath);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
int BUFFER=40960;
byte data[] = new byte[BUFFER];
for(String filePah:filePaths)
{
File file=new File(filePah);
FileInputStream fi = new FileInputStream(file);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(file.getName());
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
原文來自:應用開發筆記