What is the difference between using File.separator
and a normal /
in a Java Path-String?
In contrast to double backslash \\\\
Although it doesn't make much difference on the way in, it does on the way back.
Sure you can use either '/' or '\' in new File(String path), but File.getPath() will only give you one of them.
You use File.separator
because someday your program might run on a platform developed in a far-off land, a land of strange things and stranger people, where horses cry and cows operate all the elevators. In this land, people have traditionally used the ":" character as a file separator, and so dutifully the JVM obeys their wishes.
The pathname for a file or directory is specified using the naming conventions of the host system. However, the File class defines platform-dependent constants that can be used to handle file and directory names in a platform-independent way.
Files.seperator defines the character or string that separates the directory and the file com- ponents in a pathname. This separator is '/', '\' or ':' for Unix, Windows, and Macintosh, respectively.
As the gentlemen described the difference with variant details.
I would like to recommend the use of the Apache Commons io api, class FilenameUtils
when dealing with files in a program with the possibility of deploying on multiple OSs.
Late to the party. I'm on Windows 10 with JDK 1.8 and Eclipse MARS 1.
I find that
getClass().getClassLoader().getResourceAsStream("path/to/resource");
works and
getClass().getClassLoader().getResourceAsStream("path"+File.separator+"to"+File.separator+"resource");
does not work and
getClass().getClassLoader().getResourceAsStream("path\to\resource");
does not work. The last two are equivalent. So... I have good reason to NOT use File.separator.
"Java SE8 for Programmers" claims that the Java will cope with either. (pp. 480, last paragraph). The example claims that:
c:\Program Files\Java\jdk1.6.0_11\demo/jfc
will parse just fine. Take note of the last (Unix-style) separator.
It's tacky, and probably error-prone, but it is what they (Deitel and Deitel) claim.
I think the confusion for people, rather than Java, is reason enough not to use this (mis?)feature.