Difference between File.separator and slash in paths

后端 未结 14 1255
执笔经年
执笔经年 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:37

    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.

    Update: 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.

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

    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.

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

    If you are trying to create a File from some ready path (saved in database, per example) using Linux separator, what should I do?

    Maybe just use the path do create the file:

    new File("/shared/folder/file.jpg");
    

    But Windows use a different separator (\). So, is the alternative convert the slash separator to platform independent? Like:

    new File(convertPathToPlatformIndependent("/shared/folder"));
    

    This method convertPathToPlatformIndependent probably will have some kind of split by "/" and join with File.separator.

    Well, for me, that's not nice for a language that is platform independent (right?) and Java already support the use of / on Windows or Linux. But if you are working with paths and need to remember to this conversion every single time this will be a nightmare and you won't have any real gain for the application on the future (maybe in the universe that @Pointy described).

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

    portability plain and simple.

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

    If you are using Java 7, checkout Path.resolve() and Paths.get().

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

    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.

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