Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java ignore the first line of a .properties file?

I was working with an app that loads a .properties file with java.util.Properties like this:

Properties _properties = new Properties();
_properties.load(new FileInputStream("app.properties"));

The properties file (initially) was this:

app=myApp
dbLogin=myDbLogin
version=0.9.8.10
server=1
freq=10000
stateGap=360000

The strange thing was that when I called _properties.getProperty("app"), it always returned null, however I could load all of the other properties without any issues. I solved the problem by adding a comment to the top of the properties file, then everything worked fine.

My question is: Why does Java do this? I can't seem to find any documentation about this, and it seems counter-intuitive.

like image 791
brokethebuildagain Avatar asked Jul 17 '14 17:07

brokethebuildagain


2 Answers

Thanks to @KonstantinV.Salikhov and @pms for their help in hunting this down; I decided to post the answer that was discovered to save people hunting through the comments.

The problem was that my file was the wrong encoding, as mentioned here: http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html

The load(Reader) / store(Writer, String) methods load and store properties from and to a character based stream in a simple line-oriented format specified below. The load(InputStream) / store(OutputStream, String) methods work the same way as the load(Reader)/store(Writer, String) pair, except the input/output stream is encoded in ISO 8859-1 character encoding.

(Emphasis mine).

I changed the encoding of the properties file to ISO-8859-1 and everything worked.

like image 62
brokethebuildagain Avatar answered Sep 23 '22 03:09

brokethebuildagain


Java does not handle the BOM correctly – you can see it in the properties as key. It is possible to save the file UTF-8 but without BOM. In vim for instance

:set nobomb

See vim wiki

like image 29
karlsebal Avatar answered Sep 26 '22 03:09

karlsebal