File.separator vs FileSystem.getSeparator() vs System.getProperty(“file.separator”)?

后端 未结 2 1636
清酒与你
清酒与你 2020-12-04 14:05

There seems to be three identical ways to get the platform-dependent \"file separator\" platform-independently:

  • java.io.File.separator

2条回答
  •  粉色の甜心
    2020-12-04 14:20

    If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

    This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

    The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

    So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

提交回复
热议问题