使用java怎么壓縮文件并下載?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
1、ZIP文件格式
[local file header + file data + data descriptor]{1,n} + central directory + end of central directory record
即
[文件頭+文件數據+數據描述符]{此處可重復n次}+核心目錄+目錄結束標識當壓縮包中有多個文件時,就會有多個[文件頭+文件數據+數據描述符]
(1)創建壓縮包前準備
//定義壓縮包存在服務器的路徑 String path = request.getSession().getServletContext().getRealPath("/WEB-INF/fileTemp"); //創建路徑 File FilePath = new File(path + "/file"); if (!FilePath.exists()) { FilePath.mkdir(); } String path = FilePath.getPath() + "/"; //定義導出壓縮包的名稱 String title ="問價壓縮包"; //壓縮包格式 String fileNamezip = title + ".zip"; String zipPath = path + fileNamezip; //創建一個ZIP輸出流并實例化緩沖區域 ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath))); //設置編碼格式(解決linux出現亂碼) out.setEncoding("gbk"); //定義字節數組 byte data[] = new byte[2048]; //獲取文件記錄(獲取文件記錄代碼省略) List FileList =。。。; if (!FileList.isEmpty()) { ExportUtil util = new ExportUtil(title,title, request, response, FilePath.getPath()); }
(2)刪除壓縮包之前的數據,創建壓縮包
util.startZip(FilePath.getPath());
(3)循環將需要壓縮的文件放到壓縮包中
for (int i = 0; i < FileList.size(); i++) {
fileVo fileVo=FileList.get(i);
export(fileVo,request,response,title,FilePath.getPath(),fileName);
}
------
public void export(fileVo fileVo, HttpServletRequest request,
HttpServletResponse response, String title,String path, String fileName) {
FileOutputStream fileOutputStream = null;
try {
File dirFile = null;
int i = fileVo.getName().lastIndexOf(".");
if(i!=-1){//存在文件類型
fileName1 = fileName1 + "." + (fileVo.getName()).substring(i+1);
}
boolean bFile = false;
String mkdirName = path + File.separatorChar + title;
dirFile = new File(mkdirName);
if(!dirFile.exists()) {
dirFile.getParentFile().mkdirs();
}
if (dirFile.isDirectory()) {
path = mkdirName + File.separatorChar + fileName1;
} else {
bFile = dirFile.mkdirs();
}
if (bFile) {
path = mkdirName + File.separatorChar + fileName1;
}
fileOutputStream = new FileOutputStream(path.replace("*", ""));
String fileName = URLEncoder.encode(fileName1, "UTF-8");
if (fileName.length() > 110) {
fileName = new String(fileName1.getBytes("gb2312"), "ISO8859-1");
}
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ Utf8Util.toUtf8String(fileName) + "\"");
//讀取文件流輸出到到另一個位置
fileVo.getFileIo(fileOutputStream);
fileOutputStream.close();
} catch (Exception e) {
logger.error("異常:原因如下"+e.getMessage(), e);
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.error("異常:原因如下"+e1.getMessage(), e1);
}
}
}(4)壓縮完成,關閉輸出流。
util.entdZip(FilePath.getPath());
java生成壓縮文件示例代碼擴展
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class CompressedFileUtil {
/**
* 默認構造函數
*/
public CompressedFileUtil(){
}
/**
* @desc 將源文件/文件夾生成指定格式的壓縮文件,格式zip
* @param resourePath 源文件/文件夾
* @param targetPath 目的壓縮文件保存路徑
* @return void
* @throws Exception
*/
public void compressedFile(String resourcesPath,String targetPath) throws Exception{
File resourcesFile = new File(resourcesPath); //源文件
File targetFile = new File(targetPath); //目的
//如果目的路徑不存在,則新建
if(!targetFile.exists()){
targetFile.mkdirs();
}
String targetName = resourcesFile.getName()+".zip"; //目的壓縮文件名
FileOutputStream outputStream = new FileOutputStream(targetPath+"\\"+targetName);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));
createCompressedFile(out, resourcesFile, "");
out.close();
}
/**
* @desc 生成壓縮文件。
* 如果是文件夾,則使用遞歸,進行文件遍歷、壓縮
* 如果是文件,直接壓縮
* @param out 輸出流
* @param file 目標文件
* @return void
* @throws Exception
*/
public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{
//如果當前的是文件夾,則進行進一步處理
if(file.isDirectory()){
//得到文件列表信息
File[] files = file.listFiles();
//將文件夾添加到下一級打包目錄
out.putNextEntry(new ZipEntry(dir+"/"));
dir = dir.length() == 0 ? "" : dir +"/";
//循環將文件夾中的文件打包
for(int i = 0 ; i < files.length ; i++){
createCompressedFile(out, files[i], dir + files[i].getName()); //遞歸處理
}
}
else{ //當前的是文件,打包處理
//文件輸入流
FileInputStream fis = new FileInputStream(file);
out.putNextEntry(new ZipEntry(dir));
//進行寫操作
int j = 0;
byte[] buffer = new byte[1024];
while((j = fis.read(buffer)) > 0){
out.write(buffer,0,j);
}
//關閉輸入流
fis.close();
}
}
public static void main(String[] args){
CompressedFileUtil compressedFileUtil = new CompressedFileUtil();
try {
compressedFileUtil.compressedFile("G:\\zip", "F:\\zip");
System.out.println("壓縮文件已經生成...");
} catch (Exception e) {
System.out.println("壓縮文件生成失敗...");
e.printStackTrace();
}
}
}關于使用java怎么壓縮文件并下載問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。