是否有Java实用程序将转换String路径以使用正确的文件分隔符char?

我开发了许多用Java操作文件的类。 我正在开发一个Linux机器,并且幸福地键入了new File("path/to/some/file"); 。 当提交时,我意识到该项目的其他一些开发人员正在使用Windows。 我现在想调用一个方法,该方法可以接受"/path/to/some/file"forms的字符串,并根据操作系统返回正确分隔的路径。

例如:
在Windows上, "path/to/some/file"成为"path\\to\\some\\file"
在Linux上它只返回给定的String。

我意识到不会花很长时间来敲定一个可以做到这一点的正则表达式,但我不打算重新发明轮子,并且更喜欢经过适当测试的解决方案。 如果将它内置到JDK中会很好,但是如果它是一些小型F / OSS库的一部分也很好。

那么是否有一个Java实用程序将转换String路径以使用正确的文件分隔符char?

Apache Commons拯救了(再次)。 Commons IO方法FileNameUtils 。 separatorsToSystem()将做你想要的。

毋庸置疑,Apache Commons IO除此之外还会做很多事情,值得关注。

"/path/to/some/file"实际上可以在Windows Vista和XP下运行。

 new java.io.File("/path/to/some/file").getAbsoluteFile() > C:\path\to\some\file 

但它仍然不可移植,因为Windows有多个根源 。 因此必须以某种方式选择根目录。 相对路径应该没有问题。

编辑:

Apache commons io对unix和windows以外的env 没有帮助。 Apache io源代码 :

 public static String separatorsToSystem(String path) { if (path == null) { return null; } if (isSystemWindows()) { return separatorsToWindows(path); } else { return separatorsToUnix(path); } } 

使用新的Java 7,它们包含了一个名为Paths的类,这使您可以完全按照自己的意愿行事 (请参阅http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html )

这是一个例子:

 String rootStorePath = Paths.get("c:/projects/mystuff/").toString(); 

这就是Apache commons-io所做的,展开了几行代码:

 String separatorsToSystem(String path) { if (res==null) return null; if (File.separatorChar=='\\') { // From Windows to Linux/Mac return res.replace('/', File.separatorChar); } else { // From Linux/Mac to Windows return res.replace('\\', File.separatorChar); } } 

因此,如果您想避免额外的依赖,请使用它。

你有选择使用吗?

 System.getProperty("file.separator") 

构建表示路径的字符串?

对于7年后尝试这样做的人来说,apache commons separatorsToSystem方法已被移动到FilenameUtils类:

 FilenameUtils.separatorsToSystem(String path) 

我认为Java Paths中存在这个漏洞。

String rootStorePath = Paths.get(“c:/ projects / mystuff /”)。toString();

如果您在具有您需要使用的文件系统的系统上运行它,则可以正常运行。 正如所指出的,它使用了当前的OS文件系统。

我需要使用windows和linux之间的路径,比如将文件从一个文件复制到另一个文件。 虽然使用“/”每个作品我猜你是否使用所有Java命令,但我需要进行sftp调用,所以使用/或file.separator等…对我没有帮助。 我无法使用Path(),因为它将我的转换为我现在“运行”的默认文件系统。

Java需要的是:
`on windows system:Path posixPath = Paths.get(“/ home / mystuff”,FileSystem.Posix); stay / home / mystuff /并且不会转换为\ home \ mystuff

在Linux系统上:字符串winPath = Paths.get(“c:\ home \ mystuff”,FileSystem.Windows).toString();`保留c:\ home \ mystuff并且不会转换为/ c:/ home / mystuff

类似于使用字符集:

URLEncoder.encode(“不管这里”,“UTF-8”)。getBytes();

PS我也不想加载一个完整的apache io jar文件来做一些简单的事情。 在这种情况下,他们没有我的建议。

不应该说:

 "path"+File.Seperator+"to"+File.Seperator+"some"+File.Seperator+"file" 
 String fileName = Paths.get(fileName).toString(); 

与Windows完美配合,至少即使是混合路径也是如此

C:\ Users \用户名/ MyProject的\ myfiles文件/ MyFolder文件

 c:\users\username\myproject\myfiles\myfolder 

抱歉没有检查Linux会对上面做什么,但是Linux文件结构又不同,所以你不会搜索这样的目录