2

これが私の BeanIO xml 構成ファイルです。

<beanio xmlns="http://www.beanio.org/2011/01"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.beanio.org/2011/01 http://www.beanio.org/2011/01    /mapping.xsd">
  <stream name="Test" format="delimited">
    <record name="TestRow" minOccurs="1" maxOccurs="unbounded" class="com.company.TestRow">
      <field name="transactionDate" type="date" format="MM/dd/yyyy"/>
      <field name="userId" type="string"/>
      <field name="clientName" type="string"/>
    </record>
  </stream>
</beanio>

問題は、このxmlファイルを呼び出してファイルを解析するクラスによって「MM/dd/yyyy」を動的に設定する必要があることです。日付形式はユーザー設定に依存するためです。

それはなんとかできますか?

4

4 に答える 4

4

これを試してください、うまくいくはずです。

マッピング ファイルで、デフォルトの DateTypeHandler のタイプ ハンドラーを定義します。

<typeHandler name="dateTypeHandler" class="org.beanio.types.DateTypeHandler" />

フィールドでそのハンドラーを使用します。必要なのはそれだけです。

<field name="transactionDate" typeHandler="dateTypeHandler" format="MM/dd/yyyy"/>
于 2013-03-02T19:29:21.123 に答える
3

うまくいくはずですが、間違いなくハックです。まず、次のようなカスタム タイプ ハンドラーを作成します。

package example;
import org.beanio.types.DateTypeHandler;

public class ClientDateTypeHandler extends DateTypeHandler {
    private static ThreadLocal<String> datePattern = new ThreadLocal<String>();

    public ClientDateTypeHandler() {
        setPattern(datePattern.get());
    }

    public static void setDatePattern(String s) {
        datePattern.set(s);
    }
}

次に、型ハンドラーをマッピング ファイルに登録します。

<typeHandler type="java.util.Date" class="example.ClientDateTypeHandler" />

最後に、StreamFactory を使用してマッピング ファイルをロードする前に、 ClientDateTypeHandler.setDatePattern(...) を呼び出します。

興味深いユースケース、私はそれを考えていませんでした。

于 2012-03-03T02:33:14.817 に答える
1

もう 1 つの例:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.beanio.types.TypeConversionException;
import org.beanio.types.TypeHandler;

import com.google.common.base.Strings;

public class TimestampHandler implements TypeHandler {
private SimpleDateFormat dateFormat = new SimpleDateFormat("MMddyyyy");

@Override
public Object parse(String text) throws TypeConversionException {
    if (Strings.isNullOrEmpty(text)) {
        return null;
    }
    try {
        return dateFormat.parse(text);
    } catch (ParseException ex) {
        throw new TypeConversionException(ex);
    }
}

@Override
public String format(Object value) {
    if (value == null || value.toString().isEmpty()) {
        return "";
    }
    return dateFormat.format(value);
}

@Override
public Class<?> getType() {
    return java.sql.Timestamp.class;
}

}
于 2015-06-25T16:55:31.123 に答える