我有下面的java类:
class DeviceUser{
private String d1;
@CsvBind
private Long u1;
@CsvBind
private Long lt;
@CsvBind
private DeviceUser ref;
//getters and setters
}
我想将存储在 DeviceUser 对象中的数据写入 .csv 文件。
输出应该是:
输出.csv:
设备ID,6111,1200,设备ID,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"));
关于java - 将java对象写入.csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40213551/