package parseWithModel.complete; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Iterator; /** * This class is part of a demo to demonstrate how csv data can be parsed using Java * This class uses the CSVReader to read a CSV file and read the file line by line * This part of the demo will use UserModel.java and will create an object for each line */ public class ModelDataParser { /** * The path of the csv from the root */ private static final String CSV_FILENAME = "users-with-header.csv"; /** * This method reads the csv file and prints out the data from the file after * reading the file line by line * * @param args */ public static void main(String[] args) { InputStream stream = ModelDataParser.class.getResourceAsStream("/data/" + CSV_FILENAME); if(stream == null) { System.err.println("File not found: " + CSV_FILENAME); System.exit(1); } Reader reader = new BufferedReader(new InputStreamReader(stream)); CsvToBean csvToBean = new CsvToBeanBuilder(reader) .withType(UserModel.class) .withIgnoreLeadingWhiteSpace(true) .withSeparator(',') .build(); Iterator csvUserIterator = csvToBean.iterator(); while(csvUserIterator.hasNext()) { UserModel csvUser = csvUserIterator.next(); System.out.println("Name : " + csvUser.getName()); System.out.println("Email : " + csvUser.getEmail()); System.out.println("=========================="); } } }