我有一个CSV文件pets.csv
:
NUMBER,NAME,TYPE
1,Jack,Dog
2,Russel,Cat
3,Great,Mouse
对于每个pets
,我都有一个自定义类:
@JsonPropertyOrder({ "NUMBER", "NAME", "TYPE" })
public class Pet {
public String number;
public String name;
public String type;
}
然后在main
类中,我希望将数据从pets.csv
提取到List<Pet>
中:
public static void main(String[] args) throws IOException {
List<Pet> pets = readFile(Path.of("pets.csv"));
pets.forEach(pet -> System.out.println(pet.name));
}
public static List<Pet> readFile(Path csvFile) throws IOException {
try(MappingIterator<Pet> petIter = new CsvMapper()
.readerWithTypedSchemaFor(Pet.class).readValues(csvFile.toFile())) {
return petIter.readAll();
}
}
然而,代替具有输出:
NAME
Jack
Russel
Great
我得到了:
NUMBER
1
2
3
我做错了什么?:)
1条答案
按热度按时间vojdkbi01#
在以下情况下重新创建并完美工作:
所以,把它们小写。希望这对你有帮助:)