json 格式转 csv 格式文件
引入 csv 文件依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
json 文件转换成 csv 文件
对于 csv 文件,第一行是表头。本示例假设 json 文件中第一行代表一个 json 对象,生成 csv 文件表头只有一列,即:"test"
/**
* 固定csv头名
*/
public static String[] tableHeaderArr = {"test"};
private static void testValidSkuGenerateV3() {
//1. 读入 json 格式的文件
String file = FileUtil.read("/Users/xxx/test/quake_file/input/yyy.txt", null);
String[] jsonObjs = file.split(System.getProperty("line.separator"));
List<Object[]> requestList = new ArrayList<>(jsonObjs.length);
for (String jsonObjStr : jsonObjs) {
try {
//将每一个 json 解析成 对象
SgCouponValidSkuRequest request = JSON.parseObject(jsonObjStr, SgCouponValidSkuRequest.class);
System.out.println(JSON.toJSONString(request));
String result = JacksonUtils.serialize(request);
requestList.add(new Object[]{result});
} catch (Exception e) {
System.out.println(e);
}
}
byte[] bytes = ExportCsvUtil.writeCsvAfterToBytes(ExportCsvUtil.tableHeaderArr, requestList);
try {
ExportCsvUtil.saveFile("/Users/xxx/test/quake_file/output/yyy.csv", bytes);
} catch (Exception e) {
System.out.println(e);
}
}
保存 csv 文件格式的工具类
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class ExportCsvUtil {
private static final Logger logger = LoggerFactory.getLogger(ExportCsvUtil.class);
/**
* 固定csv文件的表头名称
*/
public static String[] tableHeaderArr = {"test"};
/**
* 写CSV并转换为字节流
* @param tableHeaderArr 表头
* @param cellList 数据
* @return
*/
public static byte[] writeDataAfterToBytes(String[] tableHeaderArr, List<String> cellList) {
byte[] bytes = new byte[0];
ByteArrayOutputStream byteArrayOutputStream = null;
OutputStreamWriter outputStreamWriter = null;
BufferedWriter bufferedWriter = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8);
bufferedWriter = new BufferedWriter(outputStreamWriter);
//excel文件需要通过文件头的bom来识别编码,而CSV文件格式不自带bom,所以写文件时,需要先写入bom头,否则excel打开乱码
bufferedWriter.write(new String(ByteOrderMark.UTF_8.getBytes()));
//写表头
StringBuilder sb = new StringBuilder();
String tableHeader = String.join(",", tableHeaderArr);
sb.append(tableHeader + StringUtils.CR + StringUtils.LF);
for (String rowCell : cellList) {
sb.append(rowCell + StringUtils.CR + StringUtils.LF);
}
bufferedWriter.write(sb.toString());
bufferedWriter.flush();
//把输出流转换字节流
bytes = byteArrayOutputStream.toString(StandardCharsets.UTF_8.name()).getBytes();
return bytes;
} catch (IOException e) {
logger.error("writeDataAfterToBytes IOException:{}", e.getMessage(), e);
} finally {
try {
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
logger.error("iostream close IOException:{}", e.getMessage(), e);
}
}
return bytes;
}
/**
* 写CSV并转换为字节流
* @param headers 表头
* @param cellList 表数据
* @return
*/
public static byte[] writeCsvAfterToBytes(String[] headers,List<Object[]> cellList) {
byte[] bytes = new byte[0];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
CSVPrinter csvPrinter = null;
try {
//创建csvPrinter并设置表格头
csvPrinter = new CSVPrinter(bufferedWriter, CSVFormat.DEFAULT.withHeader(headers));
//写数据
csvPrinter.printRecords(cellList);
csvPrinter.flush();
bytes = byteArrayOutputStream.toString(StandardCharsets.UTF_8.name()).getBytes();
} catch (IOException e) {
logger.error("writeCsv IOException:{}", e.getMessage(), e);
} finally {
try {
if (csvPrinter != null) {
csvPrinter.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
logger.error("iostream close IOException:{}", e.getMessage(), e);
}
}
return bytes;
}
public static void saveFile(String filename, byte[] data) throws Exception {
if (data != null) {
File file = new File(filename);
if (file.exists()) {
file.delete();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(data, 0, data.length);
fos.flush();
fos.close();
}
}
}