java后台生成zip打包文件


/**
     * 
     * @param zipFile  壓縮包文件對象
     * @param listKey  壓縮的圖片物理地址
     * @return
     */
    public static boolean packageZip(File zipFile,List<String> listKey){
        //圖片打包操作
        ZipOutputStream zipStream = null;
        FileInputStream zipSource = null;
        BufferedInputStream bufferStream = null;
        try {
            zipStream = new ZipOutputStream(new FileOutputStream(zipFile));// 用這個構造最終壓縮包的輸出流
//            zipSource = null;// 將源頭文件格式化為輸入流
            
            for (String picKey : listKey) {
                
                File file = new File(picKey);
                logger.info("uppic zipFile: " + picKey );
                zipSource = new FileInputStream(file);

                byte[] bufferArea = new byte[1024 * 10];// 讀寫緩沖區

                // 壓縮條目不是具體獨立的文件,而是壓縮包文件列表中的列表項,稱為條目,就像索引一樣
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipStream.putNextEntry(zipEntry);// 定位到該壓縮條目位置,開始寫入文件到壓縮包中

                bufferStream = new BufferedInputStream(zipSource, 1024 * 10);// 輸入緩沖流
                int read = 0;

                // 在任何情況下,b[0] 到 b[off] 的元素以及 b[off+len] 到 b[b.length-1]
                // 的元素都不會受到影響。這個是官方API給出的read方法說明,經典!
                while ((read = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
                    zipStream.write(bufferArea, 0, read);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            logger.error("zipStream下載文件報錯:", e);
            return false;
        } finally {
            // 關閉流
            try {
                if (null != bufferStream)
                    bufferStream.close();
                if (null != zipStream)
                    zipStream.close();
                if (null != zipSource)
                    zipSource.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                logger.error("close stream下載文件報錯:", e);
                return false;
            }
        }
        return true;
    }

//test code
List<String> listKey = new ArrayList<String>();
        listKey.add("C:/AtCarPic22/2014-7-10/101165903/0.png");
        listKey.add("C:/AtCarPic22/2014-7-10/101165903/3.png");
        
        java.io.File zipFile = new java.io.File("D:/DownLoad4.zip");// 最終打包的壓縮包
        System.out.println("zipFile exists: " + zipFile.exists());
        System.out.println("zipFile size: " + zipFile.length());
        packageZip(zipFile,listKey);
        System.out.println("zipFile exists2: " + zipFile.exists());
        System.out.println("zipFile size: " + zipFile.length());

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM