LoginSignup
9
6

More than 5 years have passed since last update.

opencsvのカスタマイズ

Posted at

opencsv.jar のnullと空文字列の扱い、日付型を扱うなどのカスタマイズが微妙だったのでforkしてみました。

GitHub:jca02266/opencsv

test.java
    @Test
    public void testDate() {
        String s = "" +
                "\"2014-1-1\"\n" +
                "\"\"\n";

        ColumnPositionMappingStrategy<MockBean> strat = new ColumnPositionMappingStrategy<MockBean>();
        strat.setType(MockBean.class);

        strat.setColumnMapping("date");

        CsvToBean<MockBean> csv = new CsvToBean<MockBean>();

        csv.putPropertyEditor(Date.class, new MyDateEditor("yyyy-MM-dd"));

        List<MockBean> list = csv.parse(strat, new StringReader(s));
        assertThat(list, is(notNullValue()));
        assertThat(list.size(), is(2));

        assertThat(list.get(0).getDate(), is(new Date(2014-1900,1-1,1)));
        assertThat(list.get(1).getDate(), is(nullValue()));
    }

MyDateEditor クラスを用意して追加することで、Date型と文字列の相互変換を可能にします。
空文字列の扱いなどもこのクラスで行います。
標準の型についても独自のIntegerEditorクラスなどを用意することで空文字列をnullとして読み込めるようにしています。これを独自のクラスに差し替えることも可能です。

Editorクラスは、以下のようにPropertyEditorSupportを継承することで比較的簡単に作れます。

MyDateEditor.java
package au.com.bytecode.opencsv.bean;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyDateEditor extends PropertyEditorSupport {
    private String format;

    MyDateEditor(String formatString) {
        super();
        format = formatString;
    }

    @Override
    public String getAsText() {
        Date date = ((Date)getValue());
        if (date == null) {
            // null to empty string
            return "";
        }
        else {
            return new SimpleDateFormat(format).format(date);
        }
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Date date;
        if (text.isEmpty()) {
            // empty string to null
            setValue(null);
            return;
        }

        try {
            date = new SimpleDateFormat(format).parse(text);
        } catch (ParseException e) {
            throw new IllegalArgumentException(String.format("Cannot parse \"%s\" to Date object", text), e);
        }
        setValue(date);
    }
9
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6