Difference between File.separator and slash in paths

后端 未结 14 1220
执笔经年
执笔经年 2020-11-22 13:15

What is the difference between using File.separator and a normal / in a Java Path-String?

In contrast to double backslash \\\\

相关标签:
14条回答
  • 2020-11-22 13:24

    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.

    0 讨论(0)
  • 2020-11-22 13:25

    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.

    0 讨论(0)
  • 2020-11-22 13:26

    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.

    0 讨论(0)
  • 2020-11-22 13:32

    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.

    0 讨论(0)
  • 2020-11-22 13:33

    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.

    0 讨论(0)
  • 2020-11-22 13:33

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

    0 讨论(0)
提交回复
热议问题