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

Pacerier picture Pacerier · Nov 10, 2011 · Viewed 137.9k times · Source

There seems to be three identical ways to get the platform-dependent "file separator" platform-independently:

How do we decide when to use which?

Is there even any difference between them?

Answer

Bringer128 picture Bringer128 · Nov 10, 2011

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.