讀取CSV文件的Java類庫:Super CSV
Super CSV 是一個非常強大的Java開源類庫,用于讀,寫和處理CVS文件。它具有快速并易于與 POJO (Plain Old Java Object)結合使用。
Super CSV 提供了一些在其它CVS包中沒有發現的特性:
POJO 支持
Read or write using any old Javabean. Perform deep mapping and index-based mapping using the new Dozer extension! For the old-fashioned, you can read or write with Lists and Maps as well.
CSV 自動編碼
Forget about handling special characters such as commas and double-quotes - Super CSV will take care of that for you! All content is properly escaped/un-escaped according to the CSV specification.
高度可配置
Choose your own delimiter, quote character and line separator - or just use one of the predefined configurations. Comma-separated, tab-separated, semicolon-separated (Germany/Denmark) - it's all possible.
數據轉換
Powerful cell processors make it simple to parse input (to Booleans, Integers, Dates, etc), transform values (trimming Strings, doing regular expression replacement, etc) and format output like Dates and Numbers.
約束驗證
Verify that your data conforms to one or more constraints, such as number ranges, string lengths or uniqueness.
基于流的 I/O
Operates on streams rather than filenames, and gives you the control to flush or close the streams when you want. Write to a file, over the network, to a zip file, whatever!
static void readCSVFile(String csvFileName) { ICsvBeanReader beanReader = null; CellProcessor[] processors = new CellProcessor[] { new NotNull(), // ISBN new NotNull(), // title new NotNull(), // author new NotNull(), // publisher new ParseDate("MM/dd/yyyy"), // published date new ParseDouble() // price }; try { beanReader = new CsvBeanReader(new FileReader(csvFileName), CsvPreference.STANDARD_PREFERENCE); String[] header = beanReader.getHeader(true); Book bookBean = null; while ((bookBean = beanReader.read(Book.class, header, processors)) != null) { System.out.printf("%s %-30s %-30s %-20s %tD $%.2f", bookBean.getIsbn(), bookBean.getTitle(), bookBean.getAuthor(), bookBean.getPublisher(), bookBean.getPublished(), bookBean.getPrice()); System.out.println(); } } catch (FileNotFoundException ex) { System.err.println("Could not find the CSV file: " + ex); } catch (IOException ex) { System.err.println("Error reading the CSV file: " + ex); } finally { if (beanReader != null) { try { beanReader.close(); } catch (IOException ex) { System.err.println("Error closing the reader: " + ex); } } } }