将java obejct写入.csv

时间:2016-10-24 08:10:53

标签: java file opencsv

我有以下java类:

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

我想将存储在DeviceUser对象中的数据写入.csv文件。

你能帮我解决这个问题吗?

输出应为:
output.csv:
DEVICEID,6111,1200,DEVICEID,6111,1200,

1 个答案:

答案 0 :(得分:2)

在课堂上添加以下方法:

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;
}

现在使用以下内容:

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

虽然它会起作用,但这并不是你想要的。要将对象写入文件,最好编写JSON。我建议Google Gson

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