溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用java怎么壓縮文件并下載

發(fā)布時間:2021-02-18 14:25:59 來源:億速云 閱讀:175 作者:Leah 欄目:開發(fā)技術(shù)

使用java怎么壓縮文件并下載?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

1、ZIP文件格式

[local file header + file data + data descriptor]{1,n} + central directory + end of central directory record

[文件頭+文件數(shù)據(jù)+數(shù)據(jù)描述符]{此處可重復(fù)n次}+核心目錄+目錄結(jié)束標(biāo)識當(dāng)壓縮包中有多個文件時,就會有多個[文件頭+文件數(shù)據(jù)+數(shù)據(jù)描述符]

2、壓縮和下載步驟

(1)創(chuàng)建壓縮包前準(zhǔn)備

//定義壓縮包存在服務(wù)器的路徑
String path = request.getSession().getServletContext().getRealPath("/WEB-INF/fileTemp");
//創(chuàng)建路徑
File FilePath = new File(path + "/file");
if (!FilePath.exists()) {
FilePath.mkdir();
}
String path = FilePath.getPath() + "/";
//定義導(dǎo)出壓縮包的名稱
String title ="問價壓縮包";
//壓縮包格式
String fileNamezip = title + ".zip";
String zipPath = path + fileNamezip;
//創(chuàng)建一個ZIP輸出流并實例化緩沖區(qū)域
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));
//設(shè)置編碼格式(解決linux出現(xiàn)亂碼)
out.setEncoding("gbk");
//定義字節(jié)數(shù)組
byte data[] = new byte[2048];
//獲取文件記錄(獲取文件記錄代碼省略)
List FileList =。。。;
if (!FileList.isEmpty()) {
ExportUtil util = new ExportUtil(title,title,
request, response, FilePath.getPath());
}

(2)刪除壓縮包之前的數(shù)據(jù),創(chuàng)建壓縮包

util.startZip(FilePath.getPath());

(3)循環(huán)將需要壓縮的文件放到壓縮包中

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)壓縮完成,關(guān)閉輸出流。

util.entdZip(FilePath.getPath());

java生成壓縮文件示例代碼擴(kuò)展

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 {
    /**
     * 默認(rèn)構(gòu)造函數(shù)
     */
    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 生成壓縮文件。
     *                  如果是文件夾,則使用遞歸,進(jìn)行文件遍歷、壓縮
     *       如果是文件,直接壓縮
     * @param out  輸出流
     * @param file  目標(biāo)文件
     * @return void
     * @throws Exception 
     */
    public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{
        //如果當(dāng)前的是文件夾,則進(jìn)行進(jìn)一步處理
        if(file.isDirectory()){
            //得到文件列表信息
            File[] files = file.listFiles();
            //將文件夾添加到下一級打包目錄
            out.putNextEntry(new ZipEntry(dir+"/"));

            dir = dir.length() == 0 ? "" : dir +"/";

            //循環(huán)將文件夾中的文件打包
            for(int i = 0 ; i < files.length ; i++){
                createCompressedFile(out, files[i], dir + files[i].getName());         //遞歸處理
            }
        }
        else{   //當(dāng)前的是文件,打包處理
            //文件輸入流
            FileInputStream fis = new FileInputStream(file);

            out.putNextEntry(new ZipEntry(dir));
            //進(jìn)行寫操作
            int j =  0;
            byte[] buffer = new byte[1024];
            while((j = fis.read(buffer)) > 0){
                out.write(buffer,0,j);
            }
            //關(guān)閉輸入流
            fis.close();
        }
    }

    public static void main(String[] args){
        CompressedFileUtil compressedFileUtil = new CompressedFileUtil();

        try {
            compressedFileUtil.compressedFile("G:\\zip", "F:\\zip");
            System.out.println("壓縮文件已經(jīng)生成...");
        } catch (Exception e) {
            System.out.println("壓縮文件生成失敗...");
            e.printStackTrace();
        }
    }
}

關(guān)于使用java怎么壓縮文件并下載問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI