简体   繁体   中英

Java Properties, getting file path

logpath = LoggerUtils.getProperties().getProperty("log.path");
System.out.println("logpath: " + logpath);

The above code returns:

logpath: C:UsersMauriceDesktopLogs

In the properties file is:

log.path    C:\Users\Maurice\Desktop\Logs

How do I retain the file separators? I want this to work on Linux as well and not just Windows.

Actually, you need to put this in the property file:

log.path    C:\\Users\\Maurice\\Desktop\\Logs

See this:

more precisely the load method:

Scroll down a bit and you will see this among other things:

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'.

Backslash \\ is an escape character that is silently dropped otherwise.

In a property file, you need to either use forward slashes:

C:/Users/Maurice/Desktop/Logs

Or, escaped backslashes:

C:\\Users\\Maurice\\Desktop\\Logs

You need to escape the slashes as they are special characters. See: Java Properties backslash

The Java properties file format dictates that the backslash character (" \\ ") escapes the character that follow it, so to get a literal windows path you must have:

logpath: C:\\Users\\Maurice\\Desktop\\Logs

However, Java will convert path separator characters for you automatically to suit the runtime platform, so you can avoid this nuisance by always using forward slashes:

logpath: C:/Users/Maurice/Desktop/Logs

You can store the Properties to file first , then load it again to use. Properties will take care of escaping/ unescaping anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM