What is the difference between using File.separator
and a normal /
in a Java Path-String?
In contrast to double backslash \\
platform independence seems not to be the reason, since both versions work under Windows and Unix.
public class SlashTest {
@Test
public void slash() throws Exception {
File file = new File("src/trials/SlashTest.java");
assertThat(file.exists(), is(true));
}
@Test
public void separator() throws Exception {
File file = new File("src" + File.separator + "trials" + File.separator + "SlashTest.java");
assertThat(file.exists(), is(true));
}
}
To rephrase the question, if /
works on Unix and Windows, why should one ever want to use File.separator
?
portability plain and simple.
"Java SE8 for Programmers" claims that the Java will cope with either. (pp. 480, last paragraph). The example claims that:
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.