What is the difference between using File.separator
and a normal /
in a Java Path-String?
In contrast to double backslash \\\\
With the Java libraries for dealing with files, you can safely use /
(slash, not backslash) on all platforms. The library code handles translating things into platform-specific paths internally.
You might want to use File.separator
in UI, however, because it's best to show people what will make sense in their OS, rather than what makes sense to Java.
Update: I have not been able, in five minutes of searching, to find the "you can always use a slash" behavior documented. Now, I'm sure I've seen it documented, but in the absense of finding an official reference (because my memory isn't perfect), I'd stick with using File.separator
because you know that will work.
Although using File.separator to reference a file name is overkill (for those who imagine far off lands, I imagine their JVM implementation would replace a /
with a :
just like the windows jvm replaces it with a \
).
However, sometimes you are getting the file reference, not creating it, and you need to parse it, and to be able to do that, you need to know the separator on the platform. File.separator helps you do that.
If you are trying to create a File from some ready path (saved in database, per example) using Linux separator, what should I do?
Maybe just use the path do create the file:
new File("/shared/folder/file.jpg");
But Windows use a different separator (\
). So, is the alternative convert the slash separator to platform independent? Like:
new File(convertPathToPlatformIndependent("/shared/folder"));
This method convertPathToPlatformIndependent
probably will have some kind of split by "/" and join with File.separator.
Well, for me, that's not nice for a language that is platform independent (right?) and Java already support the use of /
on Windows or Linux. But if you are working with paths and need to remember to this conversion every single time this will be a nightmare and you won't have any real gain for the application on the future (maybe in the universe that @Pointy described).
portability plain and simple.
If you are using Java 7, checkout Path.resolve() and Paths.get().
Well, there are more OS's than Unix and Windows (Portable devices, etc), and Java is known for its portability. The best practice is to use it, so the JVM could determine which one is the best for that OS.