Java Properties, getting file path

我与影子孤独终老i 提交于 2019-12-22 05:47:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!