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?
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?
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.
FileSystem
instance for each file system you dealt with. –
Perceptible FileSystem
would the app show? –
Chimerical 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.
java.io
deprecated in favor of java.nio
? –
Chimerical java.io
is a bit lower level than java.nio
, but still very and widely useful. You can see the differences here: blogs.oracle.com/slc/entry/javanio_vs_javaio. nio
does not replace io
, it extends it in multiple ways (and uses io
under the hood). –
Uniplanar © 2022 - 2024 — McMap. All rights reserved.