File.separator vs FileSystem.getSeparator() vs System.getProperty(“file.separator”)?
似乎有三种相同的方法可以独立于平台获取平台相关的“文件分隔符”:
<一href="http://download.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getSeparator%28%29">
java.nio.file.FileSystems.getDefault ().getSeparator();
我们如何决定何时使用哪个?
他们之间有什么区别吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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 toSystem.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.如果您的代码不跨越文件系统边界,即您只使用一个文件系统,那么请使用
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 asjava.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.