通過(guò)對(duì)數(shù)據(jù)壓縮算法的簡(jiǎn)要介紹,利用java.util.zip包實(shí)現(xiàn)數(shù)據(jù)的壓縮與解壓,并擴(kuò)展到在網(wǎng)絡(luò)傳輸方面如何應(yīng)用java.util.zip包現(xiàn)數(shù)據(jù)壓縮與解壓。供廣大java愛(ài)好者以及開(kāi)發(fā)者學(xué)習(xí)使用,節(jié)約了開(kāi)發(fā)者時(shí)間,是當(dāng)前比較流行的壓縮代碼。
部分代碼介紹:
/**
* 功能:把 sourceDir 目錄下的所有文件進(jìn)行 zip 格式的壓縮,保存為指定 zip 文件
* @param sourceDir 如果是目錄,eg:D:\\MyEclipse\\first\\testFile,則壓縮目錄下所有文件;
* 如果是文件,eg:D:\\MyEclipse\\first\\testFile\\aa.zip,則只壓縮本文件
* @param zipFile 最后壓縮的文件路徑和名稱,eg:D:\\MyEclipse\\first\\testFile\\aa.zip
*/
public File doZip(String sourceDir, String zipFilePath)
throws IOException {
File file = new File(sourceDir);
File zipFile = new File(zipFilePath);
ZipOutputStream zos = null;
try {
// 創(chuàng)建寫(xiě)出流操作
OutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
zos = new ZipOutputStream(bos);
String basePath = null;
// 獲取目錄
if(file.isDirectory()) {
basePath = file.getPath();
}else {
basePath = file.getParent();
}