3

I have a CSV file that's created by a program other than the one I'm writing, so I can't change the headers. The headers for the file are ControllerID,Event,Number,ReaderID,Timestamp,TransactionID,. I have specified the same headers to the CSVPrinter I'm using to insert a row into the same CSV. However, when the printer adds a record, it adds a header line before the new record, as can be seen below:

0,1,2688229830,3,2018-09-03 13:54,63
ControllerID,Event,Number,ReaderID,Timestamp,TransactionID
0,1,4900920,2,2018-09-03,15:15,176492

The code in question looks like this:

/* Add an entry to the TransactionLog CSV */
private static boolean logTransaction (
  int cid, int rid, boolean freeExit, long tsMS, long accNum, String reason
) {
  boolean added = false;
  int evt = freeExit ? 8 : 1;
  File transactLog = new File(Locations.getDatabaseDir(), "TransactLog.csv"),

  CSVFormat shortFormat = CSVFormat.DEFAULT.withQuote(null)
    .withAllowMissingColumnNames(true)/*.withTrailingDelimiter(true)*/
    .withHeader(Transaction.getHeader(false));
  // Attempt to read the last transaction ID and add 1 to it, to be used as ID of new transaction
  try (
    CSVParser shortParser = new CSVParser(new FileReader(transactLog), shortFormat);
    CSVPrinter shortWriter = new CSVPrinter(new FileWriter(transactLog, true), shortFormat);
  ) {
    // read in all the current records, getting the transactionID of the last record
    List<CSVRecord> shortRecords = shortParser.getRecords();
    int newTransId = 1;
    if (!shortRecords.isEmpty()) {
      CSVRecord last = shortRecords.get(shortRecords.size() - 1);
      String lastTransactionId = last.get("TransactionID");
      // add one to last transaction ID
      try {
        newTransId = Integer.parseInt(lastTransactionId) + 1;
      } catch (IllegalArgumentException IAEx) {
        newTransId = shortRecords.size() + 1;
        LOGGER.warn("Failed to determine last transaction ID from CSV ("
          + lastTransactionId + "); setting to recordCount (" + newTransId + ") ..."
        );
      }
    }
    // write the new transaction record
    Transaction t = new Transaction(cid, evt, accNum, rid, tsMS, newTransId, reason);
    List<String> tValues = t.asList(false), fValues = t.asList(true);
    shortWriter.printRecord(tValues);
    shortWriter.flush();
    added = true;
  } catch (IOException IOEx) {
    added = false;
    LOGGER.error(Util.getErrorTrace(
      "Failed to write transaction to \"" + transactLog.getAbsolutePath() + "\" CSV", IOEx
    ));
  }

  return added;
}

The code for a transaction POJO is omitted, as it is not relevant to the problem.

How do I prevent the CSVPrinter from outputting a header line prior to outputting the row? (The CSV file already contains a header row.)

Agi Hammerthief
  • 2,114
  • 1
  • 22
  • 38

1 Answers1

6

In order to not output a header line, you need to add .withSkipHeaderRecord(true) to the CSVFormat instance used with the CSVPrinter, as below:

CSVFormat skipFormat = CSVFormat.DEFAULT.withQuote(null)
  .withAllowMissingColumnNames(true).withTrailingDelimiter(true)
  .withHeader(Transaction.getHeader(false))
  .withSkipHeaderRecord(true).withIgnoreEmptyLines(true);

The call to .withIgnoreEmptyLines(true) is optional. It's included so as not to preserve empty/blank lines.

Note: If you want to output a header line as the first line in a file, when it's created, you can change .withSkipHeaderRecord(true) to .withSkipHeaderRecord(csvFile.exists()). This works because the file doesn't exist just prior to creation, but does exist on the next write of a record.

Agi Hammerthief
  • 2,114
  • 1
  • 22
  • 38