daily pastebin goal
36%
SHARE
TWEET

Untitled

a guest Aug 12th, 2017 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Parses a csv file into a list of beans.
  3.  *
  4.  * @param <T> the type of the bean
  5.  * @param filename the name of the csv file to parse
  6.  * @param fieldDelimiter the field delimiter
  7.  * @param beanClass the bean class to map csv records to
  8.  * @return the list of beans or an empty list there are none
  9.  * @throws FileNotFoundException if the file does not exist
  10.  */
  11. public static <T> List<T> parseCsvFileToBeans(final String filename,
  12.                           final char fieldDelimiter,
  13.                           final Class<T> beanClass) throws FileNotFoundException {
  14.   CSVReader reader = null;
  15.   try {
  16.     reader = new CSVReader(new BufferedReader(new FileReader(filename)),
  17.                            fieldDelimiter);
  18.     final HeaderColumnNameMappingStrategy<T> strategy =
  19.                                          new HeaderColumnNameMappingStrategy<T>();
  20.     strategy.setType(beanClass);
  21.     final CsvToBean<T> csv = new CsvToBean<T>();
  22.     return csv.parse(strategy, reader);
  23.   } finally {
  24.     if (reader != null) {
  25.       try {
  26.           reader.close();
  27.       } catch (final IOException e) {
  28.           // ignore
  29.       }
  30.     }
  31.   }
  32. }
RAW Paste Data
Top