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|
Leave a Reply