文件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;
@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();
}
public String genAttachmentFileName(String cnName, String defaultName) {
try {
cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
} catch (Exception e) {
cnName = defaultName;
}
return cnName;
}
}