-2

I am processing a file as the following and closing it. Later, I do some more processing and get some ID that I want to append to all rows in the previous CSV generated. So all rows will have the same value.

My initial code of creating and appending data to csv:

    private StringBuilder stringBuilder = new StringBuilder(); 
    public void writeToFile(String[] tIds, PrintWriter printWriter) throws DataNotFoundException {
        int rowCount = 0;
        for(String id: tIds) {
            Data data = util.getData(id);
            csvHelper.prepareFileData(data, this.stringBuilder);
            rowCount++;
            
            if (rowCount == CHUNK_SIZE) {
                printWriter.println(this.stringBuilder.toString());
                this.stringBuilder = new StringBuilder();
                rowCount = 0;
            }
        }
        printWriter.close();
    }

Now further processing returns me some processedID that I want to append to all rows as a new column.

One option is this:

public void appendAgain(String processedId) {
        
                     BufferedReader br = new BufferedReader(new FileReader(feedFile));
            String output = "";
            String line;
            while ((line = br.readLine()) != null) {
                output += line.replace(",", "," + alertId + ",");
            }
            FileWriter fw = new FileWriter(feedFile, false); //false to replace file contents, your code has true for append to file contents
            fw.write(output);
            fw.flush();
            fw.close();
}

public void prepareFileForData(Data data, StringBuilder sb) {
   // map values from data to sb
   sb.append(data.getId());
   sb.append(",");
   sb.append(data.getName()); 
   .. and so on
}

Please comment on a better way or any suggestions on the current one. Thanks!

Atihska
  • 4,803
  • 10
  • 56
  • 98

1 Answers1

1

Do it as a sed command:

sed -i '' 's/$/,<myProcessedID>/' myfile.csv

Which you can run in a terminal or from java using ProcessBuilder.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Any other alternative? – Atihska Jul 13 '21 at 19:13
  • This is the simplest. You could do it in Java by reading the file in line by line and write out the new lines to a new file, then delete the old file and rename the new file to the old file name, but that’s a lot more code. – Bohemian Jul 13 '21 at 19:17