0

I am trying to write some contents from one csv file to another csv file using BeanIO. I am able to get the contents but the header is not writing to destination file. I don know how to fix this. Please some one help me on this. Following is the code

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();

the code is written inside a method. And I also want to remove the carriage return(\r) from the output. Thanks in advance.

user3632475
  • 21
  • 1
  • 4

2 Answers2

1

I got the answer from the Google Groups thread which utilizes a class for the header and then sets the fields to ignore, basically overriding. I did not want to create a dedicated class so instead I re-used the map class as follows:

<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>
Mark Ashworth
  • 164
  • 12
0

You may use the this util method to easily create a Header without any additional class or XML configuration.

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
  }
deFreitas
  • 4,196
  • 2
  • 33
  • 43