java產生zip包

來源:互聯網
上載者:User

標籤:pen   imp   fileinput   random   ++   臨時檔案   檔案夾   gets   伺服器   

package common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
/** 壓縮單個檔案*/
public static void zipFile(String filepath ,String zippath) {

//String s = UUID.randomUUID().toString();為了怕後面刪除這個臨時檔案是刪除到同一個檔案

//這裡filepath為要打包的檔案夾的路徑String filepath = ServletActionContext.getServletContext().getRealPath("upload/notice/"+s+"/");

//zippath為產生的zip包的路徑String zippath = ServletActionContext.getServletContext().getRealPath("upload/notice/"+s+"/week-job.zip");這裡產生的就是個week-job.zip包

//ServletActionContext.getServletContext().getRealPath();獲得伺服器位址
InputStream input = null;
ZipOutputStream zipOut = null;
try {
File file = new File(filepath);
File zipFile = new File(zippath);
input = new FileInputStream(file);
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
System.out.println("zip "+filepath+" to "+zippath);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
input.close();
zipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/** 一次性壓縮多個檔案,檔案存放至一個檔案夾中*/
public static void zipMultiFile(String filepath ,String zippath) {
try {
File file = new File(filepath);// 要被壓縮的檔案夾
File zipFile = new File(zippath);
InputStream input = null;
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
if(file.isDirectory()){
File[] files = file.listFiles();
for(int i = 0; i < files.length; ++i){
input = new FileInputStream(files[i]);
zipOut.putNextEntry(new ZipEntry(file.getName() + File.separator + files[i].getName()));
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
input.close();
}
}else{//否則,則調用壓縮單個檔案的方法
zipFile(filepath, zippath);
}
zipOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}

java產生zip包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.