Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

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?

1 Answer

0 votes
by (46k points)
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.

 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.

Browse Categories

...