问题
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.
回答1:
Actually, you need to put this in the property file:
log.path C:\\Users\\Maurice\\Desktop\\Logs
See this:
- http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
more precisely the load
method:
- http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)
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.
回答2:
In a property file, you need to either use forward slashes:
C:/Users/Maurice/Desktop/Logs
Or, escaped backslashes:
C:\\Users\\Maurice\\Desktop\\Logs
回答3:
You need to escape the slashes as they are special characters. See: Java Properties backslash
回答4:
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
回答5:
You can store the Properties
to file first, then load it again to use. Properties
will take care of escaping/ unescaping anything.
来源:https://stackoverflow.com/questions/9371288/java-properties-getting-file-path