<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.8</version> </dependency> import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class CSVReaderExample { public static void main(String[] args) throws IOException { String fileName = "data.csv"; List<Person> persons = new ArrayList<>(); FileReader reader = new FileReader(fileName); CSVParser parser = CSVFormat.DEFAULT.withHeader().parse(reader); for (CSVRecord record : parser) { String name = record.get("Name"); int age = Integer.parseInt(record.get("Age")); String city = record.get("City"); Person person = new Person(name, age, city); persons.add(person); } parser.close(); reader.close(); for (Person person : persons) { System.out.println(person); } } } class Person { private String name; private int age; private String city; @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", city='" + city + '\'' + '}'; } }


上一篇:
下一篇:
切换中文