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

发布于 2024-12-14 19:40:10 字数 588 浏览 3 评论 0原文

似乎有三种相同的方法可以独立于平台获取平台相关的“文件分隔符”:

我们如何决定何时使用哪个?

他们之间有什么区别吗?

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

How do we decide when to use which?

Is there even any difference between them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别再吹冷风 2024-12-21 19:40:10

System.getProperties() 可以通过调用 System.setProperty(String key, String value) 或使用命令行参数 -Dfile.separator=/< /code>

File.separator 获取默认文件系统的分隔符。

FileSystems.getDefault() 获取默认文件系统。

FileSystem.getSeparator() 获取文件系统的分隔符。请注意,作为一种实例方法,如果您需要代码在一个 JVM 中的多个文件系统上运行,您可以使用此方法将默认文件系统之外的不同文件系统传递给您的代码。

System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/

File.separator gets the separator for the default filesystem.

FileSystems.getDefault() gets you the default filesystem.

FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.

帅气称霸 2024-12-21 19:40:10

如果您的代码不跨越文件系统边界,即您只使用一个文件系统,那么请使用java.io.File.separator

正如所解释的,这将为您提供 FS 的默认分隔符。正如 Bringer128 所解释的,System.getProperty("file.separator") 可以通过命令行选项覆盖,并且不像 java.io.File.separator 那样安全。 。

最后一个 java.nio.file.FileSystems.getDefault().getSeparator(); 是在 Java 7 中引入的,因此如果您希望代码可移植,您最好暂时忽略它跨旧的 Java 版本。

因此,这些选项中的每一个都几乎与其他选项相同,但又不完全相同。选择一款适合您需求的产品。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文