Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Properties backslash

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

like image 277
JavaIsGreat Avatar asked Apr 26 '11 01:04

JavaIsGreat


People also ask

How do you backslash in properties file?

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, \.

What does backward slash do in Java?

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.

What does 2 backslashes mean in Java?

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.

How do I escape the special characters in properties file?

In my case, two leading '\\' working fine for me.


2 Answers

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("\\", "\\\\"))); 
like image 69
Bala R Avatar answered Sep 18 '22 17:09

Bala R


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 
like image 39
CoolBeans Avatar answered Sep 21 '22 17:09

CoolBeans