Java导出txt文件,简单实用

    /**
     * 导出txt文件
     * @throws Exception 
     */
    @RequestMapping("/exportNoticeTxt")
    public void exportNoticeTxt(HttpServletResponse response) throws Exception {
        // 设置响应的内容类型
        response.setContentType("text/plain");
        // 设置文件头
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("消息列表.txt", "UTF-8"));
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            List<Notice> list = noticeService.getNoticeList();
            StringBuffer text = new StringBuffer();
            int size = list.size();
            int c = 1;
            for (Notice notice : list) {
                String content = notice.getContent();
                text.append(content);
                if(c < size) {
                    text.append("\r\n");//换行符
                }
                c++;
            }
            buff.write(text.toString().getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(buff != null) {
                    buff.close();
                }
                if(outStr != null) {
                    outStr.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

 

导出的txt文件:

Java导出txt文件,简单实用

 

页面文件上传格式限制:

https://blog.****.net/weixin_40989555/article/details/105881380