Groovy/Java: Handling Byte Order Marks When Reading a File

PROBLEM

Given a file with the following content:-

10,20

When reading the file:-

def inputStream = new FileInputStream('test.csv')
def value = inputStream.text.trim()

println "|${value}|"

… the following values are printed:-

| 10,20|

Even though the value is trimmed, there is still a leading space in front of text.

A further inspection reveals the leading space is not a regular space:-

// first character is not a space
assert value.charAt(0) != (char) ' '

// ASCII value: 65279 vs 32
assert (int) value.charAt(0) != (int) ((char) ' ').charValue()

SOLUTION

Some editors prepend a special Unicode character called a byte order mark (BOM) to the file.

The simplest way to remove this special character is to leverage Apache Commons IO’s BOMInputStream:-

def inputStream = new BOMInputStream(new FileInputStream('test.csv'))
def value = inputStream.text.trim()

println "|${value}|"

… and now, the values are printed correctly:-

|10,20|
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s