Creating CSV file with different datasets


Lately I’ve been into Java (as part of programming in Android apps) and I had to code a logic that takes different datasets (for example data about game, data about player stats, different headers) and writes them in single CSV file. This is not a task when you simply write 2D array of string to a file with .csv extension and call it a day. Because there are multiple dataset you need to have some offset defined for each of them so the datasets don’t get overwritten.

Because the last time I’ve been coding day-to-day in Java was in high schools and first year of university, it was quite a challenge to come up with good/efficient solution. I’ve tried many unsuccessful inefficient solutions then lost motivation, leave a project for a day to stagnate, tackled it again and finally got a solution which I think is the simplest and efficient one.

Here is the instruction for it:

  1. Create a CSV object with empty values which has a dimension of total rows and columns it’s going to need to contain all datasets in it.
  2. Each dataset (in String[][] format) has associated coordinates (x,y) that denotes when it starts in our final CSV object. Iterate over dataset with double for loop so you can have access to indices and write the string being at (i,j) to CSV object on position (x+i, c+j)

It’s like painting a picture on a paper. You start with a blank paper (predefined dimensions). Then you draw an object on it. When you finish with drawing the first object, you draw another but on different location on the paper so the two objects don’t overlap.