文件下载类

1 篇文章 0 订阅
1 篇文章 0 订阅

文件工具类

package com.isp.train.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

//import org.apache.commons.io.IOUtils;


public class CommonFile {
	//解压文件
	public static boolean unzip(String zipPath, String descDir) {
        File zipFile = new File(zipPath);
        boolean flag = false;
        File pathFile = new File(descDir);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }
        ZipFile zip = null;
        try {
            zip = new ZipFile(zipFile, Charset.forName("gbk"));//防止中文目录,乱码
            for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
                ZipEntry entry = (ZipEntry)entries.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zip.getInputStream(entry);
                //指定解压后的文件夹+当前zip文件的名称
                String outPath = (descDir+zipEntryName).replace("/", File.separator);
                //判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
                if(!file.exists()){
                    file.mkdirs();
                }
                //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if(new File(outPath).isDirectory()){
                    continue;
                }
                //保存文件路径信息(可利用md5.zip名称的唯一性,来判断是否已经解压)
                //System.err.println("当前zip解压之后的路径为:" + outPath);
                OutputStream out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[2048];
                int len;
                while((len=in.read(buf1))>0){
                    out.write(buf1,0,len);
                }
                in.close();
                out.close();
            }
            flag = true;
            //必须关闭,要不然这个zip文件一直被占用着,要删删不掉,改名也不可以,移动也不行,整多了,系统还崩了。
            zip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
	//创建文件夹
	public static  File buildFile(String fileName,boolean isDirdecory){
		
		File target = new File(fileName);
		if(isDirdecory){
			target.mkdirs();
		}else{
			if(!target.getParentFile().exists()){
				target.getParentFile().mkdirs();
				target = new File(target.getAbsolutePath());
			}
		}
		return target;
		
	}
	//删除时不删除指定的文件夹
    public static void delNotDir(File file){
        File[] f = file.listFiles();
        for (int i = 0; i < f.length; i++) {
            if (f[i].isDirectory()) {
                delNotDir(f[i]);
            }
            //System.out.println(f[i].getPath());
            f[i].delete();
        }

    }
  //删除时同时删除指定的文件夹
    public static void deleteAll(File file) {

        if (file.isFile() || file.list().length == 0) {
            file.delete();
            //System.out.println(file.getPath());
        } else {
            for (File f : file.listFiles()) {
                deleteAll(f); // 递归删除每一个文件

            }
            file.delete(); // 删除文件夹
            //System.out.println(file.getPath());
        }
    }
    public static boolean deletefile(String delpath) throws Exception {
		try {
 
			File file = new File(delpath);
			// 当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 true
			if (!file.isDirectory()) {
				file.delete();
			} else if (file.isDirectory()) {
				String[] filelist = file.list(); 
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + "\\" + filelist[i]);
					if (!delfile.isDirectory()) {
						delfile.delete();
						System.out.println(delfile.getAbsolutePath() + "删除文件成功");
					} else if (delfile.isDirectory()) {
						deletefile(delpath + "\\" + filelist[i]);
						System.out.println(file + "ssss");
					}
				}
				if (!file.toString().equals("D:\\file")) {                    //选择不删除自身文件夹
					System.out.println(file.toString() + "lllllll");
					file.delete();
				}
			}
 
		} catch (FileNotFoundException e) {
			System.out.println("deletefile() Exception:" + e.getMessage());
		}
		return true;
	}
    /**
     * 将相对路径转化为HDFS文件路径
     * @author adminstrator
     * @since 1.0.0
     * @param dstPath 相对路径,比如:/data
     * @return java.lang.String
     */
    public static String generateHdfsPath(String dstPath){
        String hdfsPath = "";
        if(dstPath.startsWith("/")){
            hdfsPath += dstPath;
        }else{
            hdfsPath = hdfsPath + "/" + dstPath;
        }

        return hdfsPath;
    }
    	/**
    	 * 
    	
    	 * <p>Title: download</p>  
    	
    	 * <p>Description:下载文件 </p>  
    	
    	 * @param response
    	 * @param path
    	 * @param fileName
    	 * @return
    	 */
	 public static HttpServletResponse download(HttpServletResponse response,String path, String fileName) {
	        try {
	            // path是指欲下载的文件的路径。
	            File file = new File(path);
	            // 取得文件名。
	            //String filename = file.getName();
	            // 取得文件的后缀名。
	            //String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

	            // 以流的形式下载文件。
	            InputStream fis = new BufferedInputStream(new FileInputStream(path));
	            byte[] buffer = new byte[fis.available()];
	            fis.read(buffer);
	            fis.close();
	            // 清空response
	            response.reset();
	            // 设置response的Header
	            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
	            response.addHeader("Content-Length", "" + file.length());
	            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	            response.setContentType("application/json");//
	            toClient.write(buffer);
	            toClient.flush();
	            toClient.close();
	        } catch (IOException ex) {
	            ex.printStackTrace();
	        }
	        return response;
	    }
    /**
     * 压缩
     */

    public static void zip(String input, String output, String name) throws Exception {
    //要生成的压缩文件
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(output));
        String[] paths = input.split("\\|");
        File[] files = new File[paths.length];
        byte[] buffer = new byte[1024];
        for (int i = 0; i < paths.length; i++) {
            files[i] = new File(paths[i]);
        }
        for (int i = 0; i < files.length; i++) {
            FileInputStream fis = new FileInputStream(files[i]);
            if (files.length == 1 && name != null) {
                out.putNextEntry(new ZipEntry(name));
            } else {
                out.putNextEntry(new ZipEntry(files[i].getName()));
            }
            int len;
            // 读入需要下载的文件的内容,打包到zip文件
            while ((len = fis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.closeEntry();
            fis.close();
        }
        out.close();
    }
    /**
     * zip文件压缩
     * @param inputFile 待压缩文件夹/文件名
     * @param outputFile 生成的压缩包名字
     */

    public static void ZipCompress(String inputFile, String outputFile) throws Exception {
        File output = new File(outputFile);
    	if(!output.getParentFile().exists()) {
    		output.getParentFile().mkdir();
		}
        //创建zip输出流
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
        //创建缓冲输出流
       // BufferedOutputStream bos = new BufferedOutputStream(out);
        File input = new File(inputFile);
        
        compress(out, input,null);
       // bos.close();
        out.flush();
        out.close();
    }
    //递归压缩
    public static void compress(ZipOutputStream out, File input, String name) throws IOException {
        if (name == null) {
            name = input.getName();
        }
        //如果路径为目录(文件夹)
        if (input.isDirectory()) {
            //取出文件夹中的文件(或子文件夹)
            File[] flist = input.listFiles();

            if (flist.length == 0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入
            {
                out.putNextEntry(new ZipEntry(name + "/"));
            } else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
            {
                for (int i = 0; i < flist.length; i++) {
                	System.out.println(name + "/" + flist[i].getName());
                    compress(out,  flist[i], name + "/" + flist[i].getName());
                }
            }
        } else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
        {
            out.putNextEntry(new ZipEntry(name));
            FileInputStream fos = new FileInputStream(input);
            //BufferedInputStream bis = new BufferedInputStream(fos);
            int len;
            //将源文件写入到zip文件中
            byte[] buf = new byte[1024];
            while ((len = fos.read(buf)) >0) {
            	out.write(buf,0,len);
            }
            
            //bis.close();
            out.closeEntry();
            fos.close();
        }
    }
    public static void main(String[ ] args){
        try {
			//String Millisecond = new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date());
			//System.out.println(System.getProperty("user.dir"));
           //ZipCompress(Commons.FILE_UPLOAD_PATH, Commons.FILE_PDF_ZIP_PATH+Millisecond+".zip");
           //deletefile(Commons.FILE_PDF_ZIP_PATH);
           //ZipCompress("D:\\isp_train\\template\\", "D:\\isp_train\\"+Millisecond+".zip");
           // ZipCompress("D:\\isp_train\\template\\山东鲁能U19红队 山东鲁能U19黄队20200222.pdf", "D:\\isp_train\\"+Millisecond+".zip");
			//zip("D:\\isp_train\\template\\山东鲁能U19红队20200222.pdf|D:\\\\isp_train\\\\template\\\\山东鲁能U19红队 山东鲁能U19黄队20200222.pdf", "D:\\isp_train\\"+Millisecond+".zip",null);
        
            File fileBase=new File("D:\\isp_train\\111.pdf");
			File file=new File("D:\\isp_train\\山东鲁能U19红队20200222.pdf");
            FileInputStream fos = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fos);
            FileOutputStream outs = new FileOutputStream(fileBase);
            BufferedOutputStream out = new BufferedOutputStream(outs);
            //将源文件写入到zip文件中
            int len;
            byte[] buf = new byte[1024];
            while ((len = bis.read(buf)) >0) {
            	out.write(buf,0,len);
            }
            out.flush();// 这里一定要调用flush()方法    
            out.close();
            outs.close();
            bis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值