I am using Java Properties to read a properties file. Everything is working fine, but Properties silently drops the backslashes.
(i.e.)
original: c:\sdjf\slkdfj.jpg after: c:sdjfslkdfj.jpg
How do I make Properties not do this?
I am using the code prop.getProperty(key)
I am getting the properties from a file, and I want to avoid adding double backslashes
It is Properties. load() that's causing the problem that you are seeing as backslash is used for a special purpose. The logical line holding all the data for a key-element pair may be spread out across several adjacent natural lines by escaping the line terminator sequence with a backslash character, \.
A character preceded by a backslash (\) is an escape sequence and has a special meaning to the compiler. The following table shows the Java escape sequences. Inserts a tab in the text at this point. Inserts a backspace in the text at this point.
Mango \\ Nightangle is the encoded form, the double backslash being an escape sequence where Java expects a special character. Because of this a single backslash would lead to a compilation error.
In my case, two leading '\\' working fine for me.
It is Properties.load() that's causing the problem that you are seeing as backslash is used for a special purpose.
The logical line holding all the data for a key-element pair may be spread out across several adjacent natural lines by escaping the line terminator sequence with a backslash character, \.
If you are unable to use CoolBeans's suggestion then what you can do is read the property file beforehand to a string and replace backslash with double-backslash and then feed it to Properties.load()
String propertyFileContents = readPropertyFileContents(); Properties properties = new Properties(); properties.load(new StringReader(propertyFileContents.replace("\\", "\\\\")));
Use double backslashes c:\\sdjf\\slkdfj.jpg
Properties props = new Properties(); props.setProperty("test", "C:\\dev\\sdk\\test.dat"); System.out.println(props.getProperty("test")); // prints C:\dev\sdk\test.dat
UPDATE CREDIT to @ewh below. Apparently, Windows recognises front slashes. So, I guess you can have your users write it with front slashes instead and if you need backslashes afterwards you can do a replace. I tested this snippet below and it works fine.
Properties props = new Properties(); props.setProperty("test", "C:/dev/sdk/test.dat"); System.out.println(props.getProperty("test")); // prints C:/dev/sdk/test.dat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With