我正在尝试使用BeanIO将一些内容从一个csv文件写入另一个csv文件。我能够获取内容,但标头未写入目标文件。我不知道如何解决这个问题。请有人帮我解决这个问题。以下是代码
StreamFactory factory = StreamFactory.newInstance();
factory.load("config" + File.separatorChar
+ CSVMain.prop.getProperty("ordersmapping"));
orderWriter = factory.createWriter("salesOrder", new File(property));
for (int i = 0; i < orders.size(); i++) {
orderWriter.write(orders.get(i));
}
orderWriter.flush();
orderWriter.close();
代码编写在方法中。我还想从输出中删除回车符(\r)。提前谢谢。
我从 Google 网上论坛线程中得到了答案,该线程使用一个类作为标题,然后将字段设置为忽略,基本上是覆盖。我不想创建一个专用类,所以我重用了map
类,如下所示:
<stream name="XYZ" format="csv">
<parser>
<property name="alwaysQuote" value="true" />
</parser>
<record name="header" class="map" order="1" minOccurs="1" maxOccurs="1">
<field name="Name" default="Name" ignore="true"/>
<field name="Surname" default="Surname" ignore="
</record>
<record name="record" class="map" order="2">
<field name="Name"/>
<field name="Surname"/>
</record>
</stream>
您可以使用此 util 方法轻松创建标头,而无需任何其他类或 XML 配置。
public static void main(String[] args) {
final String factoryName = "comma delimited csv factory";
final String headerName = "CarHeader";
final var builder = new StreamBuilder(factoryName)
.format("csv")
.addRecord(Headers.of(Car.class, headerName))
.addRecord(Car.class)
;
final var factory = StreamFactory.newInstance();
factory.define(builder);
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final BeanWriter writer = factory.createWriter(factoryName, new OutputStreamWriter(bout));
try {
writer.write(headerName, null);
writer.write(new Car("Ford Ka", 2016));
writer.write(new Car("Ford Fusion", 2020));
} finally {
writer.close();
}
System.out.println(bout.toString());
// Model,Year
// Ford Ka,2016
// Ford Fusion,2020
}