I'm trying to write a CSV using openCSV 4.1, from a list of beans. However, whenever I run my programme, I get CsvBeanIntrospectionException, and then a NoSuchMethodException: Unknown property 'fieldx' on class 'class TestObject'
I have successfully used the reader counterpart to read a CSV to a list of beans.
Here's my code for the object 'TestObject':
import com.opencsv.bean.CsvBindByName;
import java.io.Serializable;
public class TestObject implements Serializable {
@CsvBindByName
int fieldx;
@CsvBindByName
int fieldy;
public TestObject() {
}
public TestObject(int x, int y) {
this.fieldx = x;
this.fieldy = y;
}
public int getX() {
return fieldx;
}
public int getY() {
return fieldy;
}
public void setX(int x) {
this.fieldx = x;
}
public void setY(int y) {
this.fieldy = y;
}
@Override
public String toString(){
return "{" + fieldx + "," + fieldy + "}";
}
}
And here's the rest.
public class Project {
public static void main(String[] args) {
TestObject t1 = new TestObject(1,2);
TestObject t2 = new TestObject(3,4);
List<TestObject> testList = new ArrayList<>();
testList.add(t1);
testList.add(t2);
Prep prep = new Prep();
try {
prep.writeCSV(testList);
} catch (IOException | CsvDataTypeMismatchException | CsvRequiredFieldEmptyException ex) {
ex.printStackTrace();
}
}
}
import com.opencsv.bean.*;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class Prep {
public void writeCSV(List<TestObject> t) throws IOException,
CsvDataTypeMismatchException,
CsvRequiredFieldEmptyException {
Writer writer = new FileWriter("testfile.csv");
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).build();
beanToCsv.write(t);
writer.close();
}
}