java apache csv_无法使用Apache Commons CSV解析CSV文件中的最后一列

童宏富
2023-12-01

循环并添加缺少的名称:

Map map = csvRecord.toMap();

for (String name : csvParser.getHeaderNames())

map.putIfAbsent(name, "");

演示

CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader();

try (CSVParser csvParser = csvFormat.parse(Files.newBufferedReader(Paths.get("test.txt")))) {

System.out.println(csvParser.getHeaderNames());

for (CSVRecord csvRecord : csvParser) {

System.out.println(csvRecord);

System.out.println(" toMap(): " + csvRecord.toMap());

Map map = csvRecord.toMap();

for (String name : csvParser.getHeaderNames())

map.putIfAbsent(name, "");

System.out.println(" fixed : " + map);

}

}

测试.txt

A,B,C,D

1,2,3,4

1,2,3

1,2

1

1,

1,,

1,,,

,,,4,,,

commons-csv-1.7.jar

)

[A, B, C, D]

CSVRecord [comment='null', recordNumber=1, values=[1, 2, 3, 4]]

toMap(): {A=1, B=2, C=3, D=4}

fixed : {A=1, B=2, C=3, D=4}

CSVRecord [comment='null', recordNumber=2, values=[1, 2, 3]]

toMap(): {A=1, B=2, C=3}

fixed : {A=1, B=2, C=3, D=}

CSVRecord [comment='null', recordNumber=3, values=[1, 2]]

toMap(): {A=1, B=2}

fixed : {A=1, B=2, C=, D=}

CSVRecord [comment='null', recordNumber=4, values=[1]]

toMap(): {A=1}

fixed : {A=1, B=, C=, D=}

CSVRecord [comment='null', recordNumber=5, values=[1, ]]

toMap(): {A=1, B=}

fixed : {A=1, B=, C=, D=}

CSVRecord [comment='null', recordNumber=6, values=[1, , ]]

toMap(): {A=1, B=, C=}

fixed : {A=1, B=, C=, D=}

CSVRecord [comment='null', recordNumber=7, values=[1, , , ]]

toMap(): {A=1, B=, C=, D=}

fixed : {A=1, B=, C=, D=}

CSVRecord [comment='null', recordNumber=8, values=[, , , 4, , , ]]

toMap(): {A=, B=, C=, D=4}

fixed : {A=, B=, C=, D=4}

 类似资料: