使用文件有什么区别。分隔符和正常的/在Java路径字符串?
与双反斜杠相比,平台独立性似乎不是原因,因为这两个版本都可以在Windows和Unix下运行。
public class SlashTest {
@Test
public void slash() throws Exception {
File file = new File("src/trials/SlashTest.java");
assertThat(file.exists(), is(true));
}
@Test
public void separator() throws Exception {
File file = new File("src" + File.separator + "trials" + File.separator + "SlashTest.java");
assertThat(file.exists(), is(true));
}
}
换句话说,如果/可以在Unix和Windows上工作,为什么要使用File.separator?
好的,让我们检查一些代码。
<init>:
String p = uri.getPath();
if (p.equals(""))
throw new IllegalArgumentException("URI path component is empty");
// Okay, now initialize
p = fs.fromURIPath(p);
if (File.separatorChar != '/')
p = p.replace('/', File.separatorChar);
然后读取fs/*(FileSystem)*/.fromURIPath() docs:
java.io.FileSystem
字符串的路径
如果需要,对给定的URI路径字符串进行后处理。这是用于
Win32,例如,将“/c:/foo”转换为“c:/foo”。路径字符串
仍然有斜杠分隔;File类中的代码将转换它们
在此方法返回之后。
这意味着filessystem . fromuripath()只在Windows中对URI路径进行后处理,因为在下一行中:
p = p.replace('/', File.separatorChar);
它将每个'/'替换为依赖于系统的seperatorChar,您可以始终确保'/'在每个操作系统中都是安全的。
如果您试图使用Linux分隔符从一些现成的路径(保存在数据库中,每个例子)创建一个文件,我应该怎么做?
也许只需要使用创建文件的路径:
new File("/shared/folder/file.jpg");
但是Windows使用不同的分隔符(\)。那么,是否可以将斜杠分隔符转换为平台无关的?如:
new File(convertPathToPlatformIndependent("/shared/folder"));
这个方法convertPathToPlatformIndependent可能会被“/”分割,并连接File.separator。
对我来说,这对于独立于平台的语言来说并不好(对吧?),而且Java已经支持在Windows或Linux上使用/。但是如果您使用的是路径,并且每次都需要记住这种转换,这将是一场噩梦,并且您将不会为应用程序在未来获得任何实际收益(可能在@Pointy所描述的宇宙中)。