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.io.Reader; public class CSVReader { public static void main(String[] args) { try (Reader reader = new FileReader("data.csv"); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT)) { for (CSVRecord csvRecord : csvParser) { String name = csvRecord.get(0); int age = Integer.parseInt(csvRecord.get(1)); String city = csvRecord.get(2); Person person = new Person(name, age, city); System.out.println(person); } } catch (IOException e) { e.printStackTrace(); } } } class Person { private String name; private int age; private String city; @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", city='" + city + '\'' + '}'; } } import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; public class CSVWriter { public static void main(String[] args) { try (Writer writer = new FileWriter("output.csv"); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT)) { List<Person> persons = new ArrayList<>(); persons.add(new Person("Alice", 25, "New York")); persons.add(new Person("Bob", 30, "San Francisco")); for (Person person : persons) { csvPrinter.printRecord(person.getName(), person.getAge(), person.getCity()); } } catch (IOException e) { e.printStackTrace(); } } } 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.io.Reader; public class CustomCSVReader { public static void main(String[] args) { try (Reader reader = new FileReader("data.csv"); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT for (CSVRecord csvRecord : csvParser) { String name = csvRecord.get(0); int age = Integer.parseInt(csvRecord.get(1)); System.out.println("Name: " + name); System.out.println("Age: " + age); } } catch (IOException e) { e.printStackTrace(); } } }


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