java 将文件或者字符串写入zip及浏览器页面显示

文件直接写入zip,包括层级目录

1.这个工具类的功能为:

  • (1)可以压缩文件,也可以压缩文件夹
  • (2)同时支持压缩多级文件夹,工具内部做了递归处理
  • (3)代码中提供了2个压缩文件的方法,一个的输入参数为文件夹路径,一个为文件列表,可根据实际需求选择方法。
  • (4)可以选择是否保留原来的目录结构,如果不保留,所有文件跑压缩包根目录去了,且空文件夹直接舍弃。注意:如果不保留文件原来目录结构,在碰到文件名相同的文件时,会压缩失败。
  • (5)碰到空的文件夹,也可以压缩      

        下面直接上代码

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileToZip {

    private static final Logger log = LoggerFactory.getLogger(FileToZip.class);

    public static void main(String[] args) {
        //方式一:压缩文件夹
        long folderStart = System.currentTimeMillis();
        fileToZip("C:\\Users\\86135\\Desktop\\test\\","C:\\Users\\86135\\Desktop\\test22.zip");
        long folderEnd = System.currentTimeMillis();
        System.out.println("Folder compression completed\ntime consuming : "+(folderEnd-folderStart));

        //方式二:压缩文件
        long fileStart = System.currentTimeMillis();
        fileToZip("C:\\Users\\86135\\Desktop\\test\\1234.txt","C:\\Users\\86135\\Desktop\\testFile22.zip");
        long fileEnd = System.currentTimeMillis();
        System.out.println("File compression completed\ntime-consuming : "+(fileEnd-fileStart));

    }

    /**
     * 创建ZIP文件
     *
     * @param sourcePath 需要压缩的文件或文件夹路径
     *                   如:C:\Users\86135\Desktop\test  或 C:\Users\86135\Desktop\test\1234.txt
     * @param zipPath    生成的zip文件存在路径(包括文件名)
     *                   如:C:\Users\86135\Desktop\test22.zip
     */
    public static void fileToZip(String sourcePath, String zipPath) {

        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            fos = new FileOutputStream(zipPath);
            zos = new ZipOutputStream(fos);
            writeZip(new File(sourcePath), "", zos);

        } catch (FileNotFoundException e) {
            log.error("创建ZIP文件失败", e);
        } finally {
            try {
                if (zos != null) {
                    zos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.error("创建ZIP文件失败", e);
            }

        }
    }

    //递归文件夹

    /**
     * 如果文件夹下有文件,则会一直递归 找到具体的文件,写入zip,此文件的父级的文件夹,会被自动创建好
     * 如果是空文件夹,则会创建对应的文件夹
     * @param file
     * @param parentPath
     * @param zos
     */
    private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.exists()) {
            if (file.isDirectory()) {//处理文件夹
                parentPath += file.getName() + File.separator;
                File[] files = file.listFiles();
                //如果文件夹具有子集继续虚幻
                if (files.length != 0) {
                    for (File f : files) {
                        //循环 直到循环到文件 写进zip
                        writeZip(f, parentPath, zos);
                    }
                } else {
                    //空目录则创建当前目录
                    //如果是空目录需要加上“/”,否则会当成文件,本人使用File.separator不成功
                    try {
                        zos.putNextEntry(new ZipEntry(parentPath+"/"));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } else {//写入文件
                BufferedInputStream fis = null;
                try {
                    //压缩文件
                    //fis = new BufferedInputStream(new FileInputStream(file));
                    //压缩字符串
                    fis = new BufferedInputStream(new ByteArrayInputStream("test文件压缩".getBytes()));

                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte[] content = new byte[1024];
                    int len;
                    while ((len = fis.read(content)) != -1) {
                        zos.write(content, 0, len);
                        zos.flush();
                    }

                } catch (FileNotFoundException e) {
                    log.error("创建ZIP文件失败", e);
                } catch (IOException e) {
                    log.error("创建ZIP文件失败", e);
                } finally {
                    try {
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (IOException e) {
                        log.error("创建ZIP文件失败", e);
                    }
                }
            }
        }
    }
}
public static String readFileContent(File file) {
	//File file = new File(fileName);
	BufferedReader reader = null;
	StringBuffer sbf = new StringBuffer();
	try {
		reader = new BufferedReader(new FileReader(file));
		String tempStr;
		while ((tempStr = reader.readLine()) != null) {
			sbf.append(tempStr).append("\n");
		}
		reader.close();
		return sbf.toString();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	return sbf.toString();
}

压缩得字符串:

替换对应方法即可,其他不变
//压缩文件
fis = new BufferedInputStream(new FileInputStream(file));
//压缩字符串
fis = new BufferedInputStream(new ByteArrayInputStream("test文件压缩".getBytes()));

2.如果需要在页面显示
controller层需要传递参数:HttpServletResponse response
ZipOutputStream zos = null; zos对象实例化方式调整
由:
fos = new FileOutputStream(zipPath);
zos = new ZipOutputStream(fos);
修改为:
OutputStream out = response.getOutputStream();
zos = new ZipOutputStream(out);

if(response!=null){
	//再将本地的压缩包输出到页面上
	response.setCharacterEncoding("UTF-8"); //设置编码字符
	response.setContentType("application/octet-stream;charset=UTF-8"); //设置下载内容类型
	response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipName + ".zip", "utf-8"));//设置下载的文件名称
	OutputStream out = response.getOutputStream();

	zos = new ZipOutputStream(out);
}

类似这种效果

本文转载自  https://blog.csdn.net/weixin_44385419/article/details/113624891

方便以后记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值