2018년 3월 30일 금요일

[Java] CSV Parser and Printer Example


1. CSV Parser and Printer Example

Downlaod: apache commons csv


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package javautility;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

public class JavaUtility {

        static String testCsvPrinter() throws IOException {
        Object[] header = { "name", "gender", "age"};        
        StringWriter f = new StringWriter();
        CSVPrinter c = new CSVPrinter(f, CSVFormat.DEFAULT);
        c.printRecord(header);
        c.printRecord(new Object[] { "Alice","female","20" });
        c.printRecord(new Object[] { "Tom","male","23" });
        f.close();
        c.close();
        System.out.println(f.toString());
        return f.toString();
    }
    
    static void testCsvParser(String data) throws IOException {
        CSVParser c = new CSVParser(new StringReader(data), CSVFormat.DEFAULT);
        List<CSVRecord> records = c.getRecords();
        for( CSVRecord r : records ) {
            for( int i=0; i < r.size(); i++ ) {
                System.out.print( r.get(i) + "," );
            }
            System.out.println();
        }
        c.close();
    }
    
    public static void main(String[] args) throws IOException {
        testCsvPrinter();
        System.out.println("----------");
        testCsvParser(testCsvPrinter());
    }
}

Result:
name,gender,age
Alice,female,20
Tom,male,23

----------
name,gender,age
Alice,female,20
Tom,male,23

name,gender,age,
Alice,female,20,
Tom,male,23,





댓글 없음:

댓글 쓰기