java反斜杠,Java Properties反斜杠

  • Post author:
  • Post category:java


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,

\.

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();

Propertied props = new Properties();

props.load(new StringReader(propertyFileContents.replace(“\\”,”\\\\”));