将 java 对象写入 .csv

Writing java object into .csv

我有下面的 java class:

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,

向您的 class 添加以下方法:

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