如何用Java将含换行的制表符分隔字符串转为CSV字符串
处理含内部换行的TSV转标准CSV
你的问题核心是TSV字段内包含换行,导致按行读取时拆分错误,已知每行固定以"test2222"结尾,我们可以基于这个标记识别完整行,再转换为标准CSV。
实现步骤(Java)
- 按固定结束标记拆分完整行:用
"test2222"作为分隔符拆分原始字符串,过滤拆分后产生的空字符串。 - 补全行结束标记:给每个拆分后的行内容补回
"test2222",恢复完整行结构。 - 转换为CSV格式:将每行的制表符替换为逗号,保留字段内的换行;若字段包含双引号,需转义为
""(符合CSV标准)。 - 拼接最终CSV:把处理后的行拼接起来,按需添加表头。
代码示例
public class TsvToCsvConverter { public static void main(String[] args) { String test = "\"abc\"\t\"cde\"\t\"fhg\"\t\"ijk\"\t\"17/01/23 10:09:50 am\"\t\"test111\"\t\"test2\"\t\"Individual\"\t\"Enclosure of Work Areas\"\t\t\"Highlight aluminium personnel lanyarded into the Haulotte boom lift with a spotter. All tools observed to be lanyarded including protection gear. \n" + "Blue glue asset card observed to be attached to the machinery, 10 year inspection of plant not required due to it being only 3yrs old. Last annual inspection august 2022 and logbook was subsequently observed. \n" + "Plant registration was all observed and the weight loads were all abided by.\"\t\"test2222\"\n" + "\"abc\"\t\"cde\"\t\"fhg\"\t\"ijk\"\t\"17/01/23 10:09:50 am\"\t\"test111\"\t\"test2\"\t\"Individual\"\t\"Enclosure of Work Areas\"\t\t\"1\"\t\"0\"\t\"Level 79\"\t\"16/01/23 11:12:50 pm\"\t\"Logistics - Construction Personnel & Material Lifts\"\t\t\t\t\t\"Schindler lift cages were observed to be free of any loose debris or material that may pose a risk of falling into the lift shaft below. L80 and L79 were observed to be compliant on both sides of the shaft.\"\t\"test2222\""; // 按结束标记拆分所有行 String[] rawRows = test.split("\"test2222\""); StringBuilder csvBuilder = new StringBuilder(); // 添加表头(根据实际字段调整) String header = "\"col1\",\"col2\",\"col3\",\"col4\",\"col5\",\"col6\",\"col7\",\"col8\",\"col9\",\"col10\",\"col11\",\"col12\",\"col13\",\"col14\",\"col15\",\"col16\""; csvBuilder.append(header).append("\n"); // 处理每一行数据 for (String row : rawRows) { row = row.trim(); if (row.isEmpty()) continue; // 补回行结束标记 String fullRow = row + "\"test2222\""; // 转CSV:制表符替换为逗号,转义字段内的双引号(按需启用) String csvRow = fullRow.replace("\"", "\"\"") .replace("\t", ","); csvBuilder.append(csvRow).append("\n"); } // 输出最终CSV String finalCsv = csvBuilder.toString().trim(); System.out.println(finalCsv); } }
关键说明
- 放弃按
\n拆分行的逻辑,改用固定结束标记"test2222",确保每个拆分结果都是完整的一行数据。 - 原始TSV的字段已用双引号包裹,直接替换制表符为逗号即可,字段内部的换行会被CSV解析器正确识别。
- 若原始字段存在双引号,启用代码中的双引号转义逻辑,符合CSV规范。
内容的提问来源于stack exchange,提问作者Brisi
相关产品推荐
相关产品推荐

