Controller.java
/**
* 导出电话号码
* @return
*/
@RequestMapping(value = "/export-phones", method = RequestMethod.GET)
public Result exportPhones(@RequestParam(required=false)String uuid, HttpServletResponse response) throws BusinessException {
service.exportPhones(uuid, response);
return success();
}
Service.java
/**
* 导出电话号码
* @throws BusinessException
*/
@SuppressWarnings("unchecked")
@Override
public void exportPhones(String uuid, HttpServletResponse response) throws BusinessException {
if (StringUtils.isBlank(uuid)) {
throw new InvalidArgumentException("uuid=" + uuid);
}
User record = userDao.getByUuid(uuid);
if (record == null) {
throw new BusinessException(ResultCode.RECORD_NOT_EXIST_ERROR.code(),
ResultCode.RECORD_NOT_EXIST_ERROR.message());
}
String phones = record.getPhones();
//[13628045433, 12345678900] 数据库存的String
List<Long> phoneList = JSONObject.parseObject(phones, ArrayList.class);//下面读取的时候会报错Long转换String
// 导出文件
response.setContentType("text/plain");
String fileName = "phone-list";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");
BufferedOutputStream buff = null;
StringBuffer write = new StringBuffer();
String enter = "\r\n";
ServletOutputStream outSTr = null;
try {
outSTr = response.getOutputStream(); // 建立
buff = new BufferedOutputStream(outSTr);
// 把内容写入文件
if (phoneList.size() > 0) {
for (int i = 0; i < phoneList.size(); i++) {
write.append(phoneList.get(i));
write.append(enter);
}
}
buff.write(write.toString().getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buff.close();
outSTr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
版权声明:本文为jinzhencs原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。