将字符串写入txt并压缩到zip包

/**
     * 将字符串写入文本文件并写入压缩包
     * @param response  response对象
     * @param fileName  下载的文件名称 (下载后需要给文件的名称)
     * @param response  字符串
     * @throws Exception
     */
    private void downloadFile(HttpServletResponse response, String fileName, String str) throws Exception {
        //设置向浏览器端传送的文件格式
        response.setContentType("text/plain");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        ZipOutputStream zip = null;

        //将字符串变成输入流
        bis = new BufferedInputStream(new ByteArrayInputStream(str.getBytes("utf-8")));
        //获取输出流
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[str.getBytes().length];
        //zip压缩文件输出流
        zip = new ZipOutputStream(bos);
        //获取zip压缩文件中的实体(test.txt为压缩文件中的文本文件名称)
        ZipEntry entry = new ZipEntry("test.txt");
        entry.setSize(str.getBytes().length);
        //将实体放入压缩文件流中
        zip.putNextEntry(entry);

        //写入
        int len = 0;
        while ((len = bis.read(buff)) != -1) {
            zip.write(buff, 0, len);
        }

    }

    /**
     * 下载方法
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping
    public String download(HttpServletResponse response) throws Exception {
        String str = "测试文本测试文本";
        downloadFile(response, "test.zip", str);
        return null;

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值