File Path separator in Java

Jadala Ajay
1 min readJun 23, 2022

--

While working on automation when setting file path we may use the file path separator such as / or \.Some use-cases are setting driver path, download directory etc.
We generally use / on UNIX and \ on Windows. The best practice is to use a separator, not to hardcode.
Let's see how we use it with Java.

We can do it in 3 ways irrespective of any platform

1.System.getProperty(“file.separator”)

public class GetFileSeparator {
public static void main(String[] args) {
// unix / , windows \
String separator = System.getProperty(“file.separator”);
System.out.println(separator);
}
}

2.FileSystems.getDefault().getSeparator() (Java NIO)

public class GetFileSeparator2 {
public static void main(String[] args) {
// unix / , windows \
String separator = FileSystems.getDefault().getSeparator();
System.out.println(separator);
}
}

3.File.separator Java IO

public class GetFileSeparator3 {
public static void main(String[] args) {
// unix / , windows \
String separator = File.separator;
System.out.println(separator);
}
}

Note: For System.getProperty("file.separator"), we can override the value by System.setProperty() or command line -Dfile.separator. Both File.separator and FileSystems.getDefault().getSeparator() will return the same separator.

--

--

Jadala Ajay

8 Years Exp Senior Automation Engineer with expertise on Selenium,RestAsured API,Postman,Cypress,WebdriverIO with prog languages Java,Javascript and Python