Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

People also ask

What is System getProperty file separator?

A file separator is platform-dependent what means in Unix we will have a different separator than in Windows OS. That's why it is important to use Java-built methods to retrieve it when we are working with files. We can get file path separator in three ways: using System. getProperty("file.

What is the file separator?

A file separator is a character that is used to separate directory names that make up a path to a particular location. This character is operating system specific. On Microsoft Windows, it is a back-slash character (), e.g. C:myprojectmyfilesome.

Why We use file separator?

The file separator is the character used to separate the directory names that make up the path to a specific location.


System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/

File.separator gets the separator for the default filesystem.

FileSystems.getDefault() gets you the default filesystem.

FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.


If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.