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
?
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.
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.
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.
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.
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.
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.