欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

java spring boot 导出/下载文本文件操作(包括写入文本文件)

最编程 2024-07-17 14:10:08
...
/** * 导出 * @return CallbackBody */ @Override public ResponseEntity<byte[]> exportLand2ndClassIndex(){ //查询表数据 List<TswatLuc2ndClassIndex> list = tswatLuc2ndClassIndexDao.queryAllClassIndex(); if (list == null || list.size() <= 0){ return null; } List txtContentList = new ArrayList(); txtContentList.add("\"value\",\"name\""); for(TswatLuc2ndClassIndex classIndex : list){ String value = classIndex.getLevel2Code(); String name = classIndex.getSwat(); txtContentList.add(value + "," + name); } //导出的文件存储目录 String fileSavePath = GisPathConfigurationUtil.getSwatLuc2ndClassIndexTxtFileSavePath(); //保存文本文件 writeToTxt(txtContentList, fileSavePath); //获取文本文件的ResponseEntity try{ ResponseEntity<byte[]> fileByte = buildResponseEntity(new File(fileSavePath)); return fileByte; }catch (Exception e){ e.printStackTrace(); return null; } } /** * 将数据写入文本文件 * @param list * @param path */ private void writeToTxt(List list,String path) { String dir = path.substring(0,path.lastIndexOf("\\")); File parent = new File(dir); if (parent != null && !parent.exists()) { parent.mkdirs(); } FileOutputStream outSTr = null; BufferedOutputStream Buff = null; String enter = "\r\n"; StringBuffer write ; try { outSTr = new FileOutputStream(new File(path)); Buff = new BufferedOutputStream(outSTr); for (int i = 0; i < list.size(); i++) { write = new StringBuffer(); write.append(list.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(); } } } //读取文件 private ResponseEntity<byte[]> buildResponseEntity(File file) throws IOException { byte[] body = null; //获取文件 InputStream is = new FileInputStream(file); body = new byte[is.available()]; is.read(body); HttpHeaders headers = new HttpHeaders(); //设置文件类型 headers.add("Content-Disposition", "attchement;filename=" + file.getName()); //设置Http状态码 HttpStatus statusCode = HttpStatus.OK; //返回数据 ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode); return entity; }