0

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,

2
  • 1
    Have you tried anything? Please, write your code from your attempt (even if not working), so people know you don't want just someone to do it for you. Googling I easily found this: howtodoinjava.com/3rd-party/… Commented Oct 24, 2016 at 8:55
  • below, sol is working fine with ref object Commented Oct 24, 2016 at 9:33

1 Answer 1

2

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"));
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for reply but because of reference, it is printing that object twice.
is the reference to the object itself or to another object??
i want , deviceId,6111,1200,deviceId,6111,1200. but is giving, deviceId,6111,1200,deviceId,6111,1200,deviceId,6111,1200
it can be same or different object of same type
@sachin10 it's not possible. My code prints 6 values. Are you sure you're using it as I wrote?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.