2

I'm reading a CSV file saved in a ContentVersion

The CSV header looks like:

FirstName,LastName,...

I'm checking to make sure the first line (header row) matches the expected column headers using this code:

ContentVersion cv = [SELECT VersionData FROM ContentVersion WHERE ...];
String csv = cv.VersonData.toString();
String[] csvHeader;
//  apply CSV Parser to csv to read first line into a array of cells csvHeader (not shown)
if (!csvHeader[0] == 'FirstName') {
  throw new MyException('Header does not match expected value FirstName in column A');
}

But the CSV header displays in the debug log as having a value of FirstName in array position 0.

Why does the string compare fail? FirstName == FirstName

1 Answer 1

3

This took a while to figure out. Here's what I did:

  • I copy-pasted the actual CSV row header FirstName and the expected CSV row header FirstName into two cells in Excel and then wrote a formula to see if they were equal. They were not! But why?

  • I then copy-pasted the actual CSV row header FirstName into a hex editor. My, my, what did I see but these hex characters:

     EF BB BF 46 69 72 73 74 4E 61 6D 65
              F  i  r  s  t  N  a  m  e 
    

EF BB BF is a Byte order mark and was added to the CSV file during the Excel save process (not the upload into a ContentVersion)

So, the code needed to be changed to remove the BOM before comparison

ContentVersion cv = [SELECT VersionData FROM ContentVersion WHERE ...];
String csv = cv.VersonData.toString().removeStart('\uFEFF'); // remove BOM
String[] csvHeader;
//  apply CSV Parser to csv to read first line into a array of cells csvHeader (not shown)
if (!csvHeader[0] == 'FirstName') { 
  throw new MyException('Header does not match expected value FirstName in column A');
}

Lesson - when two strings that look the same in the debug log compare unequal; paste them into a hex editor and see the true values.

4
  • And, of course, make sure you only remove it if it's present.
    – sfdcfox
    May 6, 2021 at 2:10
  • removeStart: Removes the specified substring only if it occurs at the beginning of the String.
    – cropredy
    May 6, 2021 at 2:12
  • I would have just removed it from the original string before splitting and everything else as a matter of legibility. Didn't say you were doing it wrong.
    – sfdcfox
    May 6, 2021 at 2:23
  • ah, good point; i'll fix
    – cropredy
    May 6, 2021 at 2:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .