场景说明:
基于hutool 生成csv文件 随机文件名【getRandomFileName()】
指定路径【path】下生成csv 这里引用了一个循环模拟数据接收 这个数据来源可以是rabbitMQ、redis等 一次性获取多条数据推送
每条数据生成一行csv 并且csv有自己的表头
当读取csv的行量【readSize()】超过最大值【csvMaxSize】时 重新生成一个带表头的文件createCsv();
如果行量没超过最大值时 继续追加数据 由于hutool没有提供直接的接口方法做追加数据:这里采纳了hutool读取csv数据【readData()】 合并新数据模式写入文件
循环推送 做了34次推送 每次推两条
由于推送每次是多条 判断当前如果小于最大值【csvMaxSize】时 就会当前量【readSize()】+ 每次推送量 会使文件实际行量大于等于最大值【csvMaxSize】 下一次推送时才能发现行量超过最大值【csvMaxSize】 出发生成新文件
测试方法:
搞一个空maven项目
放上我的pom 直接放 不用的也可以自己删吧删吧
把java代码建一个TestController 为了测试方便 一大坨都给你放这里头了
运行
访问 http://127.0.0.1:8080/swagger-ui.html
代码:
package com.dragon.controller;import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.*;import cn.hutool.core.util.CharsetUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;@Api(value = "测试")
@RestController
@RequestMapping("/test")
public class TestController {private String csvName;private String path= "D:\\cscFile\\";private int csvMaxSize=20;@Data@Setter@Getterpublic class User {private String id;private String name;private String nickname;private String sex;private String age;}/*** 获取并组装导出数据*/@ApiOperation(value = "测试连通性", httpMethod = "GET")@ResponseBody@RequestMapping(value = "/p", method = RequestMethod.GET)public void getUserList() {//创建文件件 放置表头createCsv();//模拟每次接受消息for(int i=1;i<35;i++){//模拟数据环节List userList=new ArrayList<>();User tempA = new User();//模拟每次推两条tempA.setId("AID-A:"+Integer.toString(i));tempA.setSex("A男");tempA.setName("Aname:wanger");tempA.setNickname("Anickname:Jay");tempA.setAge("A30");userList.add(tempA);User tempB = new User();tempB.setId("BID-B:"+Integer.toString(i));tempB.setSex("B男");tempB.setName("Bname:wanger");tempB.setNickname("Bnickname:Jay");tempB.setAge("B30");userList.add(tempB);//检查csv行数 超过规定重建文件List result= new ArrayList();if(readSize(path+csvName) >csvMaxSize){createCsv();}//先读取文件内容 列宽List fileCsvRows = new ArrayList<>();fileCsvRows = readData(path+csvName);if(fileCsvRows.size()>0){for(int lineKey=0;lineKeyresult.add(fileCsvRows.get(lineKey));}}//保存开始------------------------for(User user:userList){//遍历用户列表的数据 列数Field[] declaredFields =new Field[4];try {//将对象要显示的字段插入对应标题位置declaredFields[0]=user.getClass().getDeclaredField("name");declaredFields[1]=user.getClass().getDeclaredField("nickname");declaredFields[2]=user.getClass().getDeclaredField("sex");declaredFields[3]=user.getClass().getDeclaredField("id");//获取UserList对象的数据作为listValueString[] listValue = new String[declaredFields.length];for(int x=0;xdeclaredFields[x].setAccessible(true); //设置为允许操作//将属性值添加到listValue对应的索引位置下listValue[x] = String.valueOf(declaredFields[x].get(user)) ;//将listValue添加到result中}result.add(listValue);} catch (Exception e) {e.printStackTrace();}}//将组装好的结果集传入导出csv格式的工具类this.createCsvFile(result,csvName);//保存结束------------------------}}public void createCsv(){csvName=getRandomFileName("dzbs-")+".csv";//自定义标题别名,作为第一行listNameString[] listName = new String[4];listName[0]="用户名";listName[1]="用户昵称";listName[2]="性别";listName[3]="id";//获取String[]类型的数据至result中List newResult= new ArrayList();//将listName添加到result中newResult.add(listName);this.createCsvFile(newResult,csvName);}/*** 导出csv格式工具类* 创建文件并放置数据 这里放置了表头一行数据* @param result 导出数据* @param fileName 文件名*/public void createCsvFile(List result,String fileName){try {File csvFile = new File(fileName); //构造文件//导入HuTool中CSV工具包的CsvWriter类//设置导出字符类型, CHARSET_UTF_8
// CsvWriter writer = CsvUtil.getWriter(csvFile, CharsetUtil.CHARSET_UTF_8);CsvWriter writer = CsvUtil.getWriter(csvFile, CharsetUtil.CHARSET_GBK);writer.write(result); //通过CsvWriter中的write方法写入数据writer.close(); //关闭CsvWriter//保存文件FileInputStream fileInputStream=new FileInputStream(csvFile);this.saveFile(fileInputStream,csvFile.getName());}catch (Exception e){System.out.println(e);}}/*** 文件保存 覆盖保存* @param inputStream* @param fileName*/private void saveFile(InputStream inputStream, String fileName) {OutputStream os = null;try {//保存文件路径// 1K的数据缓冲 1024000 1Mbyte[] bs = new byte[1024000];// 读取到的数据长度int len;// 输出的文件流保存到本地文件File tempFile = new File(path);if (!tempFile.exists()) {tempFile.mkdirs();}os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);// 开始读取while ((len = inputStream.read(bs)) != -1) {os.write(bs, 0, len);}} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {// 完毕,关闭所有链接try {os.close();inputStream.close();} catch (IOException e) {e.printStackTrace();}}}/* ** 检查文件是否存在* 读取数据封装到实体 读取行数*/private int readSize(String fileName) {CsvReader reader = CsvUtil.getReader();//从文件中读取CSV数据int size = 0;try {CsvData data = reader.read(FileUtil.file(fileName), CharsetUtil.CHARSET_GBK);size = data.getRowCount();}catch (Exception e){System.out.println("尚未生成:"+fileName+ " --即将创建 ");}return size;}/* ** 读取数据封装到实体*/private List readData(String fileName) {CsvReader reader = CsvUtil.getReader();List scvData = new ArrayList<>();try {CsvData data = reader.read(FileUtil.file(fileName), CharsetUtil.CHARSET_GBK);scvData = data.getRows();}catch (Exception e){
// System.out.println("尚未生成:"+fileName+ " --即将创建 ");}return scvData;}public static String getRandomFileName(String pre) {SimpleDateFormat simpleDateFormat;simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");Date date = new Date();String str = simpleDateFormat.format(date);Random random = new Random();int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数return pre+ str + rannum;// 当前时间}}
4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.0 com.dragon springboot_rabbitmq_consumer v1.3 jar springboot_rabbitmq_consumer Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web log4j-api org.apache.logging.log4j log4j-to-slf4j org.apache.logging.log4j org.apache.logging.log4j log4j-core 2.16.0 log4j-api org.apache.logging.log4j org.apache.logging.log4j log4j-api 2.16.0 org.apache.logging.log4j log4j-to-slf4j 2.16.0 log4j-api org.apache.logging.log4j org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-data-jdbc 2.5.0 com.baomidou mybatis-plus-boot-starter 3.3.0 mybatis-plus-core com.baomidou io.springfox springfox-boot-starter 3.0.0 cn.hutool hutool-all 5.6.5 com.baomidou mybatis-plus-core 3.3.0 org.projectlombok lombok org.springframework.amqp spring-rabbit net.sf.json-lib json-lib 2.2.3 jdk15 commons-lang commons-lang commons-logging commons-logging com.alibaba fastjson 1.2.78 org.apache.maven.plugins maven-surefire-plugin true org.springframework.boot spring-boot-maven-plugin lib BOOT-INF/lib/ **/*.jar src/main/java **/*.properties src/main/resources