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:

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

How to save file separators? I want this to work with Linux as well, not just Windows.

+6
source share
5 answers

Actually, you need to put this in the properties 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 process the backslash character, \, before an invalid escape character as an error; the backslash is silently discarded. For example, in a Java string, the sequence "\ z" will result in a compile-time error. In contrast, this method silently removes the backslash. Therefore, this method considers two character sequences "\ b" as equivalent to one character "b".

The backslash \ is an escape character that is otherwise discarded silently.

+14
source

In the properties file, you need to either use slashes:

 C:/Users/Maurice/Desktop/Logs 

Or, resettable backslashes:

 C:\\Users\\Maurice\\Desktop\\Logs 
+4
source

You need to avoid the slash as they are special characters. See: Java Backslash Properties

+3
source

The properties file format indicates the literal path to the window that you should have:

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

However, Java will automatically convert the path delimiter characters to the runtime platform, so you can avoid this trouble by always using slashes:

 logpath: C:/Users/Maurice/Desktop/Logs 
+2
source

First you can save Properties to a file and then load it again for use. Properties will take care of slipping / undoing something.

0
source

Source: https://habr.com/ru/post/908943/


All Articles