用于从CSV文件创建对象的Java API
我正在寻找一个允许我将.csv内容映射到对象的库。
就像是:
public class Person { private String name; private int age; @CsvField("name") public String getName() { return this.name; } @CsvField("age") public int getAge() { return this.age; } }
然后说出类似的话:
final Person filledWithDataFromCsv = csvApi.load(csvFilepath, Person.class);
来自给定的CSV:
#name, age tom, 11 jim, 32
有没有人知道这样的API,或者做类似的事情。 我不希望它使用注释作为必须,我只是希望能够使用一行代码和预定义的类加载文件。
JSefa允许您注释可用于序列化和反序列化过程的Java类。 本教程演示了如何使用CsvIOFactory类。
(从教程中)注释bean就像指定值列表中项目的位置一样简单,如有必要,您需要指定转换格式:
@CsvDataType() public class Person { @CsvField(pos = 1) String name; @CsvField(pos = 2, format = "dd.MM.yyyy") Date birthDate; }
使用uniVocity解析器不会出错。 它支持各种强大的操作,并且比任何其他Java解析器快得多。
这是一个有一些例子的类:
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; // The attribute type defines which conversion will be executed when processing the value. @Trim @LowerCase // the value for the comments attribute is in the column at index 4 (0 is the first column, so this means fifth column in the file) @Parsed(index = 4) private String comments; // you can also explicitly give the name of a column in the file. @Parsed(field = "amount") private BigDecimal amount; @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; }
以下是获取TestBean
列表的TestBean
BeanListProcessor rowProcessor = new BeanListProcessor (TestBean.class); CsvParserSettings parserSettings = new CsvParserSettings(); parserSettings.setRowProcessor(rowProcessor); parserSettings.setHeaderExtractionEnabled(true); CsvParser parser = new CsvParser(parserSettings); parser.parse(getReader("/examples/bean_test.csv")); List beans = rowProcessor.getBeans();
披露:我是这个图书馆的作者。 它是开源和免费的(Apache V2.0许可证)。
我更喜欢opencsv
,它非常简单而且非常干净。
http://opencsv.sourceforge.net/
例如阅读:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv")); String [] nextLine; while ((nextLine = reader.readNext()) != null) { // nextLine[] is an array of values from the line System.out.println(nextLine[0] + nextLine[1] + "etc..."); }
CSV有很好的JDBC实现。 因此,您可以使用此类驱动程序,配置数据源以使用它,然后使用JPA(或其他)在该数据源之上进行对象关系映射。
最新版本的https://github.com/arnaudroger/SimpleFlatMapper 0.9.4现在有一个CsvMapper。 它使用标头来匹配属性名称,或者如果没有标题,则可以通过构建器指定列名称。 它支持构造函数,setter和字段注入。 从InputStream或Reader读取。 现在它也不会管理#name到name的映射。 有没有理由在csv的开头有一个#?
public class MyParser { private final CsvMapper mapper = CsvMapperFactory.newInstance().newMapper(MyObject.class); public void writeAllObjectToLambda(Writer writer, InputStream is) throws IOException { mapper.forEach(is, (o) -> writer.append(o.toString()).append("\n")); } }