SuperCSVのCsvBeanWriterでNULLを出力するサンプル
SuperCSVのCsvBeanWriterを使用してて一番困ったのが
Bean内にNULLの項目があるとNullPointerExceptionが発生すること・・・。
CsvBeanWriterのためだけにBeanを変更するのもいやだったので
CsvBeanWriterを継承してNULLを空文字として出力するように変更。
材料はこちら
org.supercsv
import java.io.Writer; import java.lang.reflect.InvocationTargetException; import org.supercsv.exception.SuperCSVReflectionException; import org.supercsv.io.CsvBeanWriter; import org.supercsv.prefs.CsvPreference; public class CsvBeanWriterEx extends CsvBeanWriter { public CsvBeanWriterEx(Writer arg0, CsvPreference arg1) { super(arg0, arg1); } /** * populate <tt>result</tt> based on the source * * @param source * @param nameMapping * @throws IllegalAccessException * @throws InvocationTargetException */ protected void fillListFromObject(final Object source , final String[] nameMapping) throws SuperCSVReflectionException { try { result.clear(); // object re-use // map results from an object by traversing the list of nameMapping and // for for( final String methodName : nameMapping ) { final Object object = cache.getGetMethod(source,methodName).invoke(source); result.add(object != null ? object : ""); } } catch(final IllegalAccessException e) { throw new SuperCSVReflectionException("Error accessingobject " + source, e); } catch(final InvocationTargetException e) { throw new SuperCSVReflectionException("Error accessingobject " + source, e); } } }
書き込みの際にCsvBeanWriterExを使用すると
BeanにNULLの項目があっても例外が発生せず空文字と出力します。