我有下面的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的deviceId, 6111, 1200, 6111, 1200,
为您的类添加以下方法:
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"));