Java导出和下载文本

如何导出和下载文本

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.util.List;

/**
 * 导出下载文本
 */
@Slf4j
public class TextDownloader {


    /**
     * 导出文本
     *
     * @param fileName   文件名,示例 : 明朝故事
     * @param response
     * @param list       内容行
     * @param extendName 扩展名称(需要带点),示例.txt
     */
    public static void exportTxt(String fileName, HttpServletResponse response, List<String> list, String extendName) {
        StringBuffer stringBuffer = new StringBuffer();
        list.forEach(c -> {
            stringBuffer.append(c).append("\n");
        });
        exportTxt(fileName, response, stringBuffer.toString(), extendName);
    }

    /**
     * 导出文本
     *
     * @param fileName
     * @param response
     * @param text
     * @param extendName
     */
    public static void exportTxt(String fileName, HttpServletResponse response, String text, String extendName) {
        log.info("导出中.............");
        String cnName = "";
        try {
            cnName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
            cnName = "default";
        }
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式
        response.addHeader("Content-Disposition", "attachment;filename="
                + cnName
                + extendName);
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(text.getBytes("UTF-8"));
            buff.flush();
            buff.close();
            log.info("导出文本结束");
        } catch (Exception e) {
            log.error("导出文本出错", e);
        } finally {
            try {
                buff.close();
                outStr.close();
            } catch (Exception e) {
                log.error("关闭流出错", e);
            }
        }
    }

}

测试

@Slf4j
@Controller
@RequestMapping("/txtdownload")
public class TxtDownloadController {


    @RequestMapping("/test")
    public void test(HttpServletRequest request, HttpServletResponse response) throws Exception {
        TextDownloader.exportTxt("明朝的故事", response,
                "明朝历史丰富多彩,以下是明朝的十大经典故事: 1. 朱元璋建立明朝:元末爆发红巾起义,朱元璋加入郭子兴队伍。1364年称吴王,史称西吴。1368年初称帝,国号大明,定都南京,标志着",
                ".txt");
    }

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值