讀取CSV文件的Java類庫:Super CSV

jopen 10年前發布 | 39K 次閱讀 Super CSV Java開發

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.baiduhome.net/lib/view/home/1389337254180

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!