读取CSV文件的Java类库:Super CSV

jopen 10年前

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);              }          }      }  }

项目主页:http://www.open-open.com/lib/view/home/1389337254180