文件IO流,读取与下载

文件IO流,读取与下载

package com.liu.demo.controller;

import com.liu.demo.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

/**
 * @author Administrator
 */
@Slf4j(topic="ArticleController")
@RestController
@ResponseBody
public class ArticleController {
    
    

    @Autowired
    private ArticleService articleService;

    @GetMapping("/exportResult")
    public void exportLog(HttpServletResponse response) throws IOException {
    
    
    	//字符串的拼接是数据库查询的结果
        //插入时间
        Date date = new Date();
        DateFormat df = DateFormat.getDateTimeInstance();
        String articleData=df.format(date);
        articleData+=articleService.getAllArticle().toString();
        articleData+="\r\n";
        exportTxt(response,articleData);
    }


    public void exportTxt(HttpServletResponse response,String text) throws IOException {
    
    
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式,设置名称格式,没有这个中文名称无法显示
        response.addHeader("Content-Disposition","attachment;filename="+ genAttachmentFileName( "查询结果", "JSON_FOR_UCC_")  + ".txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;

        outStr = response.getOutputStream();
        buff = new BufferedOutputStream(outStr);
        buff.write(text.getBytes("UTF-8"));

        buff.flush();
        buff.close();
        outStr.close();

    }


    /**
     * 防止中文文件名显示出错
     * @param cnName
     * @param defaultName
     * @return
     */
    public  String genAttachmentFileName(String cnName, String defaultName) {
    
    
        try {
    
    
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
    
    
            cnName = defaultName;
        }
        return cnName;
    }
}

猜你喜欢

转载自blog.csdn.net/liuliusix/article/details/108594097