0

I have the following data that are read from CSV file:

Class    Total     Step     Run1    Run2   Run3    Run4
Timer    15        2        10.5    3.6    5.5     8

Later, other classes will be added with variable size of runs. For example, the class Optimiser that has 6 runs will be added and the the CSV will be like:

Class     Total     Step     Run1    Run2   Run3    Run4
Timer     15        2        10.5    3.6    5.5     8
Optimiser 26        6        6       10     5       1.5    16    9

As you can see, the header is missing the Run5 and Run6.

My question is how can I update the header to include the new column names? Note that other classes might be added later with more runs than 6.

The code that I have written to write to the CSV is:

  try {
      BufferedWriter out = new BufferedWriter(new FileWriter(f, true));
      if (f.length() == 0L) {
          out.write("Class");
          out.write(",");
          out.write("Total");
          out.write(",");
          out.write("Step");
          out.write(",");
          for (int i = 1; i <= numRuns; i++) {
              out.write(String.valueOf(i));
              out.write(",");
          }
          out.write("\n");
      }

      for (int i = 0; i < classes.size(); i++) {
          out.write(classes.get(i));
          out.write(",");

          out.write(totals.get(i));
          out.write(",");

          out.write(steps.get(i));
          out.write(",");

          List<Double> runs = this.getRuns(classes.get(i));
          for (double x: runs) {
              out.write(String.valueOf(x));
              out.write(",");
          }
          out.write("\n");
      }
      out.close();

  } catch (IOException e) {
      e.printStackTrace();
  }
alexrnov
  • 2,346
  • 3
  • 18
  • 34
Adam Amin
  • 1,406
  • 2
  • 11
  • 23
  • Related - https://stackoverflow.com/questions/181408/best-way-to-write-bytes-in-the-middle-of-a-file-in-java – Dan W Feb 06 '19 at 17:23

1 Answers1

0

You should know the maximum number of runs in any row before moving to writing step you may do that by

int numRuns = 0
for (int i=0; i<classes.size(); i++) {
    int rowSize = this.getRuns(classes.get(i));
    if (rowSize > numRows) {
        numRuns = rowSize;
    }
}
hanyahmed
  • 71
  • 2