java换行写入csv文件,最后一行去掉空白行
public void Csvcreate(HttpServletRequest request, HttpServletResponse response, List<Map> list) {
String cateid = "";
List<String> datalist = new ArrayList();
for (int i = 0; i < list.size(); i++) {
Map map = list.get(i);
StringBuffer sb = new StringBuffer();
cateid = String.valueOf(map.get("CATEID"));
sb.append(map.get("CATEID"));
sb.append(",");
sb.append(map.get("CARD_NO"));
//最后一行加上
会出现空白行
if(i < list.size() - 1){
sb.append("
");
}
datalist.add(sb.toString());
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String todayFile = sdf.format(new Date());
//目录
String path = request.getSession().getServletContext().getRealPath(File.separator) + todayFile + "/";
log.debug("-------csv----" + path);
String filename = todayFile;
File file = new File(path);
if (!file.isDirectory()) {
file.mkdirs();
}
try {
//缓冲FileWriter
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path +
"stock_" + cateid + "_" + filename + ".csv")), "GBK"));
String header = "cateid,卡号
";
bw.write(header);
// 添加新的数据行
for (String str : datalist) {
bw.write(str);
bw.flush();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
File csvFile = new File(path + "stock_" + cateid + "_" + filename + ".csv");
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-strea");
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("stock_" + cateid + "_" + filename + ".csv", "UTF-8"));
fis = new FileInputStream(csvFile);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
log.info("Download successfully!");
} catch (Exception e) {
log.info("Download failed!{}", e);
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}