How to get file path separator in Java
For file path or directory separator, the Unix system introduced the slash character /
as directory separator, and the Microsoft Windows introduced backslash character \
as the directory separator. In a nutshell, this is /
on UNIX and \
on Windows.
In Java, we can use the following three methods to get the platform-independent file path separator.
System.getProperty("file.separator")
FileSystems.getDefault().getSeparator()
(Java NIO)File.separator
Java IO
1. System Property
Get the file path separator via the system Properties file.separator
.
package com.mkyong.io.howto;
public class GetFileSeparator {
public static void main(String[] args) {
// unix / , windows \
String separator = System.getProperty("file.separator");
System.out.println(separator);
}
}
2. Java NIO
Java 7, NIO FileSystems.getDefault().getSeparator()
.
package com.mkyong.io.howto;
import java.nio.file.FileSystems;
public class GetFileSeparator2 {
public static void main(String[] args) {
// unix / , windows \
String separator = FileSystems.getDefault().getSeparator();
System.out.println(separator);
}
}
3. Java IO
Java IO File.separator
example.
package com.mkyong.io.howto;
import java.io.File;
public class GetFileSeparator3 {
public static void main(String[] args) {
// unix / , windows \
String separator = File.separator;
System.out.println(separator);
}
}
4. Which One?
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 returns the same separator.
Read on this Legacy File I/O Code drawbacks, picks the Java NIO FileSystems.getDefault().getSeparator()
.
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-io