Java语言实现txt文件下载
不废话直接贴代码
@Controller
public class CpsChannelController {
/**
* 下载txt文件
*
* @return
*/
@GetMapping("/downLoadTxt")
@ResponseBody
public void downLoadTxt(HttpServletResponse response, String fileName) {
String txtName = fileName;//下载的文件名称
List<Data> list = null;//文件data,输出内容
StringBuffer txtDetail = new StringBuffer();
for(Data data : list){
txtDetail.append(data.getA());
txtDetail.append("|");//拼接格式“|”,可以自定义
txtDetail.append(data.getB());
txtDetail.append("\r\n");//换行
}
exportToTxt(response,txtDetail,txtName);
}
public static void exportToTxt(HttpServletResponse response, String txtDetail, String
txtName) {
//设置响应的字符集
response.setCharacterEncoding("utf-8");
//设置响应内容的类型
response.setContentType("text/plain");
//设置文件的名称和格式
response.addHeader(
"Content-Disposition",
"attachment; filename="
+ genAttachmentFileName(txtName, "默认名称")//设置名称格式,没有这个中文名称无法显示
+ ".txt");//通过后缀可以下载不同的文件格式
BufferedOutputStream buff = null;
ServletOutputStream outStr = null;
try {
outStr = response.getOutputStream();
buff = new BufferedOutputStream(outStr);
buff.write(txtDetail.getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (Exception e) {
log.error("导出文件文件出错,e:{}",e);
} finally {try {
buff.close();
outStr.close();
} catch (Exception e) {
log.error("关闭流对象出错 e:{}",e);
}
}
}
/**
* 防止中文名称出错
*
* @return
*/
public static String genAttachmentFileName(String cnName, String defaultName) {
try {
cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
} catch (Exception e) {
cnName = defaultName;
}
return cnName;
}
}