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文件:

 

頁面文件上傳格式限制:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章