javaweb 壓縮文件 並下載

  private static final int  BUFFER_SIZE =  1024;    
//壓縮多個文件爲ZIP格式        
    public static void toZip(List<File> srcFiles ,String path,HttpServletResponse response)throws RuntimeException, IOException {    
        FileOutputStream fileOutputStream=new FileOutputStream(path);
                long start = System.currentTimeMillis();        
                ZipOutputStream zos = null ;        
                try {        
                    zos = new ZipOutputStream(fileOutputStream);        
                    for (File srcFile : srcFiles) {        
                        byte[] buf = new byte[BUFFER_SIZE];        
                        zos.putNextEntry(new ZipEntry(srcFile.getName()));        
                        int len;        
                        FileInputStream in = new FileInputStream(srcFile);        
                        while ((len = in.read(buf)) != -1){        
                            zos.write(buf, 0, len);    
                        }
                        zos.closeEntry();        
                        in.close();
                    }        
                    long end = System.currentTimeMillis();        
                    System.out.println("壓縮完成,耗時:" + (end - start) +" ms");
        
                } catch (Exception e) {        
                  e.printStackTrace();
                }finally{
                    if(zos != null){    
                        try {    
                            zos.close();
                        } catch (IOException e) {
                           e.printStackTrace();
                        }
                    }
                }
                Tools.downfile(path, "照片.zip", response);
            }
    //下載文件
    public static void downfile(String path,String filename,HttpServletResponse response) throws IOException{
        response.setContentType("application/x-msdownload");
            
              response.addHeader("Content-Disposition","attachment;fileName="+new String(filename.getBytes(),"iso8859-1"));
             OutputStream os = response.getOutputStream(); 
            FileInputStream fis = new FileInputStream(path); 
            try{
                
                 BufferedInputStream bufferedInputStream=new BufferedInputStream(fis);
                BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(os);
                 byte[] buffer = new byte[4096];
                   int count = 0;
                while ((count=bufferedInputStream.read(buffer, 0, buffer.length))>0) {
                    bufferedOutputStream.write(buffer, 0, count);
                }
                bufferedInputStream.close();
                bufferedOutputStream.flush();
                bufferedOutputStream.close();
                os.close();
                fis.close();
            }catch(Exception e){
                 e.printStackTrace();
             }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章