使用Apache Commons CSV移除记录起始处双引号问题求助
解决Apache Commons CSV空字段自动添加双引号的问题
嘿,我来帮你搞定这个问题!你遇到的情况是因为Apache Commons CSV默认的格式配置会对空字符串字段添加双引号,而你希望空字段直接输出为空白(不带引号),同时还要保留像"12,100"这种带分隔符字段的引号,保证CSV格式正确。
下面给你两种可行的解决方案:
方案一:调整CSVFormat的格式配置
直接修改创建CSVPrinter时的格式参数,通过配置QuoteMode和空值处理规则,让空字段输出为空白且不带引号,同时保留必要的引号:
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.QuoteMode; import java.nio.file.Files; import java.nio.file.Paths; import java.io.BufferedWriter; import java.util.List; // 你的原有代码部分 String CSV_File_Path = "Sample.csv"; CSVConversion records = new CSVConversion(CSV_File_Path); List<CSVRecord> csvRecords = records.getRecords(); BufferedWriter writer = Files.newBufferedWriter(Paths.get("Sample2.csv")); // 核心配置:定制CSV格式 CSVFormat csvFormat = CSVFormat.DEFAULT .withHeader("Username", "Password", "Amount", "Timestamp") .withQuoteMode(QuoteMode.MINIMAL) // 仅当字段包含分隔符/引号/换行时加引号 .withNullString("") // 将null值输出为空字符串 .withEmptyString(""); // 空字符串直接输出为空白 CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); csvPrinter.printRecords(csvRecords); csvPrinter.flush(); csvPrinter.close();
方案二:预处理CSVRecord,转换空字符串为null
如果方案一不生效,可能是因为读取后的CSVRecord中空字段被存储为空字符串而非null。这时候可以先遍历所有记录,把空字符串转为null,再写入:
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.nio.file.Files; import java.nio.file.Paths; import java.io.BufferedWriter; import java.util.ArrayList; import java.util.List; // 你的原有代码部分 String CSV_File_Path = "Sample.csv"; CSVConversion records = new CSVConversion(CSV_File_Path); List<CSVRecord> csvRecords = records.getRecords(); BufferedWriter writer = Files.newBufferedWriter(Paths.get("Sample2.csv")); CSVFormat csvFormat = CSVFormat.DEFAULT .withHeader("Username", "Password", "Amount", "Timestamp") .withNullString(""); // null值输出为空白 CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); // 预处理每条记录,将空字符串转为null for (CSVRecord record : csvRecords) { List<String> processedValues = new ArrayList<>(); for (String value : record) { // 空字符串或null都转为null,写入时输出为空白 processedValues.add(value == null || value.trim().isEmpty() ? null : value); } csvPrinter.printRecord(processedValues); } csvPrinter.flush(); csvPrinter.close();
这两种方案都能让你得到想要的输出:空字段直接留白,不带双引号,同时带分隔符的字段依然保留引号,保证CSV格式的正确性。
内容的提问来源于stack exchange,提问作者YRKKH
相关产品推荐
相关产品推荐

