文件下载的工具类

/*
 * Copyright(C) 2000-2011 THS Technology Limited Company, http://www.ths.com.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ths.projects.DataCenterController.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 
 * @author gusg
 * @since 2017-10-21
 */
public class DownLoadUtil {
    /**
     * 把接受的全部文件打成压缩包
     * 
     * @param List
     *            <File>;
     * @param org
     *            .apache.tools.zip.ZipOutputStream
     */
    
    public static void zipFileY(List files, ZipOutputStream outputStream) {
        int size = files.size();
        for (int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }

    /**
     * 根据输入的文件与输出流对文件进行打包
     * 
     * @param File
     * @param org
     *            .apache.tools.zip.ZipOutputStream
     */
    public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
        try {
            if (inputFile.exists()) {
                /**
                 * 如果是目录的话这里是不采取操作的, 至于目录的打包正在研究中
                 */
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    // org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 关闭创建的流对象
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static HttpServletResponse downloadZip(File file,
            HttpServletResponse response) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");

            // 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(file.getName(), "UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                File f = new File(file.getPath());
                f.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    // 删除文件夹
    public static void deleteAllFilesOfDir(File path) {
        if (!path.exists())
            return;
        if (path.isFile()) {
            path.delete();
            return;
        }
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            deleteAllFilesOfDir(files[i]);
        }
        path.delete();
    }

    // 递归删除文件夹
    private void deleteFile(File file) {
        if (file.exists()) {// 判断文件是否存在
            if (file.isFile()) {// 判断是否是文件
                file.delete();// 删除文件
            } else if (file.isDirectory()) {// 否则如果它是一个目录
                File[] files = file.listFiles();// 声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) {// 遍历目录下所有的文件
                    this.deleteFile(files[i]);// 把每个文件用这个方法进行迭代
                }
                file.delete();// 删除文件夹
            }
        } else {
            System.out.println("所删除的文件不存在");
        }
    }

    // 根据路径和名称下载附件
    public static void downlodafile(String filePath, HttpServletResponse response, Map<String, Object> map)
            throws Exception {
        String temp = URLDecoder.decode(filePath, "UTF-8");
        String fileName = (String) map.get("FILE_NAME") + "."
                + (String) map.get("FILE_TYPE");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-disposition", "attachment; filename="
                + URLEncoder.encode(fileName, "UTF-8"));
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                temp));
        BufferedOutputStream bos = new BufferedOutputStream(
                response.getOutputStream());
        byte[] b = new byte[100];
        int len;
        while (-1 != (len = bis.read(b, 0, b.length))) {
            bos.write(b, 0, len);
        }
        bis.close();
        bos.close();
    }
        
     public static void downloadLocal(HttpServletResponse response,String oneFile,String fileName) throws Exception {
           
            // 读到流中
            InputStream inStream = new FileInputStream(oneFile);// 文件的存放路径
            
            // 设置输出的格式
            response.reset();
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            try {
                while ((len = inStream.read(b)) > 0)
                    response.getOutputStream().write(b, 0, len);
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
          
         /** 
         * 从网络Url中下载文件 
         * @param urlStr 
         * @param fileName 
         * @param savePath 
         * @throws IOException 
         */  
        public static void downLoadFromUrl(String urlStr,String fileName,String extensionName, File saveDir) throws IOException{  
            URL url = new URL(urlStr);    
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
                    //设置超时间为5秒  
            conn.setConnectTimeout(5*1000);  
            //防止屏蔽程序抓取而返回403错误  
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
      
            //得到输入流  
            InputStream inputStream = conn.getInputStream();    
            //获取自己数组  
            byte[] getData = readInputStream(inputStream);      
      
            if(!saveDir.exists()){  
                saveDir.mkdir();  
            }  
            File file = new File(saveDir+File.separator+fileName+extensionName);      
            FileOutputStream fos = new FileOutputStream(file);       
            fos.write(getData);   
            if(fos!=null){  
                fos.close();    
            }  
            if(inputStream!=null){  
                inputStream.close();  
            }  
      
            System.out.println("info:"+url+" download success");   
        }  
      
         /** 
         * 从输入流中获取字节数组 
         * @param inputStream 
         * @return 
         * @throws IOException 
         */  
        public static  byte[] readInputStream(InputStream inputStream) throws IOException {    
            byte[] buffer = new byte[2048];    
            int len = 0;    
            ByteArrayOutputStream bos = new ByteArrayOutputStream();    
            while((len = inputStream.read(buffer)) != -1) {    
                bos.write(buffer, 0, len);    
            }    
            bos.close();    
            return bos.toByteArray();    
        }   
   } 
        
       
      
 

  • 22
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值