Java Properties backslash

JavaProperties

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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("\\", "\\\\")));

Solution 2 - Java

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

Solution 3 - Java

Use forward slashes. There is never a need in Java to use a backslash in a filename.

Solution 4 - Java

In case you really need a backslash in a properties file that will be loaded (like for a property that is not a file path) put \u005c for each backslash character.

The backslash is treated specially in properties files as indicated in the document provided by @unhillbilly.

@EJP: Backslash is definitely needed if, for example, you wanted to store an NTLM login id in a properties file, where the format is DOMAIN\USERNAME with a backslash. This type of property is not a filename so forward slashes will not work.

Edit: @Max Nanasy: From the document (java.util.Properties load javadoc) mentioned above (emphasis mine)

>The method does not treat a backslash character, '\', before a non-valid escape character as an error; the backslash is silently dropped. For example, in a Java string the sequence "\z" would cause a compile time error. In contrast, this method silently drops the backslash. Therefore, this method treats the two character sequence "\b" as equivalent to the single character 'b'

For me, I always had trouble with backslashes in the properties file (even with double backslash '\\') unless I specified the unicode.

Solution 5 - Java

Replace \ with \\ as below:

c:\sdjf\slkdfj.jpg 

to

c:\\sdjf\\slkdfj.jpg

Solution 6 - Java

In addition to Bala R's answer I have the following solution to even keep the newline-semantic of backslashes at the end of a line.

Here is my code:

private static Reader preparePropertyFile(File file) throws IOException {

    BufferedReader reader = new BufferedReader(new FileReader(file));
    StringBuilder result = new StringBuilder();

    String line;
    boolean endingBackslash = false;

    while ((line = reader.readLine()) != null) {
        line = line.trim();
        if (endingBackslash) {

            // if the line is empty, is a comment or holds a new property
            // definition the backslash found at the end of the previous
            // line is not for a multiline property value.
            if (line.isEmpty()
                    || line.startsWith("#")
                    || line.matches("^\\w+(\\.\\w+)*=")) {

                result.append("\\\\");
            }
        }

        // if a backslash is found at the end of the line remove it
        // and decide what to do depending on the next line.
        if (line.endsWith("\\")) {
            endingBackslash = true;
            line = line.substring(0, line.length() - 1);
        } else {
            endingBackslash = false;
        }
        result.append(line.replace("\\", "\\\\"));
    }
    if (endingBackslash) {
        result.append("\\\\");
    }
    return new StringReader(result.toString());
}

private static Properties getProperties(File file) throws IOException {
    Properties result = new Properties();
    result.load(preparePropertyFile(file));
    return result;
}

Solution 7 - Java

The following code will help :

BufferedReader metadataReader = new BufferedReader(new InputStreamReader(new FileInputStream("migrateSchemaGenProps.properties")));
Properties props = new Properties();
props.load(new StringReader(IOUtils.getStringFromReader(metadataReader).replace("\\", "/")));

Solution 8 - Java

It is not realy a good thing to use backslashes in a property-file, as they are the escape character.

Nevertheless: a Windows user will trend to use them in any path... Therefore, in a single line thanks apache common IO:

params.load(new StringReader(IOUtils.toString(paramFile.toURI(), null).replaceAll("\\\\", "/")));

Solution 9 - Java

you triple use the backslash to get one: for example: key=value1\\value2 in the properties file will turn to key=value1\value2 in the java Properties object

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJavaIsGreatView Question on Stackoverflow
Solution 1 - JavaBala RView Answer on Stackoverflow
Solution 2 - JavaCoolBeansView Answer on Stackoverflow
Solution 3 - Javauser207421View Answer on Stackoverflow
Solution 4 - JavafroobleView Answer on Stackoverflow
Solution 5 - JavaDileep DondapatiView Answer on Stackoverflow
Solution 6 - JavaAlexSView Answer on Stackoverflow
Solution 7 - JavaVaibhav JainView Answer on Stackoverflow
Solution 8 - JavaOlivier FaucheuxView Answer on Stackoverflow
Solution 9 - JavaJohannes ScherbelView Answer on Stackoverflow