2017-01-07 9 views
0

オープンCsvを使ってCsvテーブルフォーマットにJava Beanを書く方法はありますか? これを実現するために利用できる他のライブラリは何ですか?Csvテーブル形式にJava Beanを書く

+0

http://stackoverflow.com/questions/30073980/java-writing-strings-to -a-csv-file http://opencsv.sourceforge.net/ – bakki

答えて

0

uniVocity-parsers Java Beanとの変換はサポートされていません。ここでは、クラスの簡単な例です:

public class TestBean { 

    // if the value parsed in the quantity column is "?" or "-", it will be replaced by null. 
    @NullString(nulls = {"?", "-"}) 
    // if a value resolves to null, it will be converted to the String "0". 
    @Parsed(defaultNullRead = "0") 
    private Integer quantity 

    @Trim 
    @LowerCase 
    @Parsed(index = 4) 
    private String comments; 

    // you can also explicitly give the name of a column in the file. 
    @Parsed(field = "amount") 
    private BigDecimal value; 

    @Trim 
    @LowerCase 
    // values "no", "n" and "null" will be converted to false; values "yes" and "y" will be converted to true 
    @BooleanString(falseStrings = {"no", "n", "null"}, trueStrings = {"yes", "y"}) 
    @Parsed 
    private Boolean pending; 
} 

、これを行う、ファイルへのインスタンスを書くこと:

Collection<TestBean> beansToWrite = someMethodThatProducesTheObjectYouWant(); 
File output = new File("/path/to/output.csv"); 
new CsvRoutines().writeAll(beansToWrite, TestBean.class, output, Charset.forName("UTF-8")); 

ライブラリは、多くの構成オプションとあなたが望むものを達成するための方法を提供しています。同じアノテーションを何度も繰り返し使用していることがわかっている場合は、メタアノテーションを定義するだけです。たとえば、代わりにすべての単一のフィールドでこれを宣言する `文字を含むフィールドの上に交換用の変換を適用します。

@Retention(RetentionPolicy.RUNTIME) 
@Inherited 
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) 
@Replace(expression = "`", replacement = "") 
@Parsed 
public @interface MyReplacement { 

@Copy(to = Parsed.class) 
String field() default ""; 

@Copy(to = Parsed.class, property = "index") 
int myIndex() default -1; 

と使用:

@Parsed 
@Replace(expression = "`", replacement = "") 
public String fieldA; 

@Parsed(field = "BB") 
@Replace(expression = "`", replacement = "") 
public String fieldB; 

@Parsed(index = 4) 
@Replace(expression = "`", replacement = "") 
public String fieldC; 

あなたは、このようなメタannotatinを作成することができますこのようなあなたのクラスで:

@MyReplacement 
public String fieldA; 

@MyReplacement(field = "BB") 
public String fieldB; 

@MyReplacement(myIndex = 4) 
public String fieldC; 
} 

私はそれが役に立ちます。

免責事項:私はこのライブラリの作者だけど、それがオープンソースとフリー(アパッチV2.0ライセンス)です

関連する問題