@Carl V. Dango,@Zsolt,@Jon,让我们重新开始。这是我的代码和错误(在底部)。您会在控制台输出中注意到前两行原始数据。第一行中的第一个字段(“item”)在输出中为空。我认为它应该是 'xx' 因为我在该列上编码了 StrReplace(" ","xx") 。我更担心的是如何在第三条记录的第 4 列中捕获空/空白。这些看起来很基本,以至于我有点沮丧,要解决这么多麻烦。
package com.mycompany.data.transfers.app;
import java.io.FileReader;
import org.supercsv.cellprocessor.ConvertNullTo;
import org.supercsv.cellprocessor.ParseBigDecimal;
import org.supercsv.cellprocessor.ParseDate;
import org.supercsv.cellprocessor.ParseInt;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.prefs.CsvPreference;
import com.mycompany.data.transfers.models.Invoice;
public class Test {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
char quote = '"';
int delimeter = 124;
String newLine = "\n";
CellProcessor[] cp = new CellProcessor[] {
new StrReplace(" ", "xx"),
null,
new ParseDate("yyyyMMdd"),
new ParseBigDecimal(),
new ConvertNullTo("0", new ParseBigDecimal()),
new ParseDate("yyyyMMdd"),
null,
new ParseDate("yyyyMMdd"),
null,
null,
null,
null,
null,
new ParseInt()
};
Invoice bean = new Invoice();
CsvBeanReader inFile = new CsvBeanReader(new FileReader("c:\\temp\\my_test_file.txt"), new CsvPreference(quote, delimeter, newLine));
while ((bean = inFile.read(bean.getClass(), new String[] {"item", "loc", "schedDate", "fracQty", "recQty",
"expDate", "poNum", "dateShip", "masterLoadId", "loadId",
"confirmationNumber", "sourceWarehouse", "purchasingGroup",
"poDistFlag" }, cp)) != null) {
System.out.println(bean);
}
}
}
Invoice [item=, loc=NEW, schedDate=Wed Nov 02 00:00:00 CDT 2011, fracQty=5, recQty=4]
Invoice [item=0006268410, loc=SHR, schedDate=Thu Nov 03 00:00:00 CDT 2011, fracQty=12, recQty=5]
Exception in thread "main" null
Parser error context: Line: 3 Column: 4 Raw line:
[0000939515, NEW, 20111102, 50, , 20111102, , 20111102, 0000000000, 0000000000, , , BBA, 1]
offending processor: org.supercsv.cellprocessor.ParseBigDecimal@17a8913
at org.supercsv.cellprocessor.ParseBigDecimal.execute(Unknown Source)
at org.supercsv.cellprocessor.ConvertNullTo.execute(Unknown Source)
at org.supercsv.util.Util.processStringList(Unknown Source)
at org.supercsv.io.CsvBeanReader.read(Unknown Source)
at com.mycompany.data.transfers.app.Test.main(Test.java:48)
Caused by: java.lang.NumberFormatException
at java.math.BigDecimal.<init>(BigDecimal.java:534)
at java.math.BigDecimal.<init>(BigDecimal.java:728)
... 5 more