Search code examples
javafileopencsv

Writing java object into .csv


I have the java class below:

class DeviceUser{
private String d1;
@CsvBind
private Long u1;
@CsvBind
private Long lt;
@CsvBind
private DeviceUser ref;
//getters and setters
}

I want to write the data, stored in the DeviceUser object, into a .csv file.

output should be:
output.csv:
deviceId,6111,1200,deviceId,6111,1200,


Solution

  • To your class add the following method:

    public String[] toArray() {
        String[] result = new String[6];
        result[0] = this.d1;
        result[1] = this.u2.toString();
        result[2] = this.lt.toString();
        result[3] = this.ref.getd1();
        result[4] = this.ref.getu2().toString();
        result[5] = this.ref.getlt().toString();
        return result;
    }
    

    And now use the following:

     CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), ',');
     // feed in your array (or convert your data to an array)
     writer.writeNext(deviceUser.toArray());
     writer.close();
    

    Although it'll work, it's not how you want to do that. For writing objects to files it's better to write JSONs. I would recommend Google Gson.

    Gson gson = new Gson();
    gson.toJson(obj, new FileWriter("yourfile.csv"));