在Java代码中将Windows样式path转换为unixpath

我正在devise为在Windows上运行的Java代码工作,并包含了很多对使用Windows样式path“System.getProperty(”user.dir“)\ trash \ blah”的文件的引用。 我负责调整它,并在Linux中部署。 有没有一种有效的方式来将所有这些path(\)转换为像“System.getProperty(”user.dir“)/垃圾/等等”中的unix风格(/)。 也许,在java或linux中使用\ as /进行一些configuration。

我重读你的问题,并意识到你可能不需要帮助写路径。 对于你想要做什么,我无法找到解决方案。 当我最近在一个项目中这样做时,我不得不花时间来转换所有路径。 此外,我假定将“user.home”作为根目录,相对来说,包含运行我的应用程序的用户的写权限。 无论如何,这里是我遇到的一些路径问题。

我重写了原始的Windows代码,如下所示:

String windowsPath = "C:\temp\directory"; //no permission or non-existing in osx or linux String otherWindowsPath = System.getProperty("user.home") + "\Documents\AppFolder"; String multiPlatformPath = System.getProperty("user.home") + File.separator + "Documents" + File.separator + "AppFolder"; 

如果你要在很多不同的地方做这个,也许写一个实用程序类并重写toString()方法,给你一遍又一遍的unix路径。

 String otherWindowsPath = System.getProperty("user.home") + "\Documents\AppFolder"; otherWindowsPath.replace("\\", File.separator); 

我的方法是使用Path对象来保存路径信息,处理连接和相对路径。 然后,调用Path的toString()来获取路径String。

为了转换路径分隔符,我更喜欢使用apache常见的io库的FilenameUtils。 它提供了三个有用的功能:

 String separatorsToSystem(String path); String separatorsToUnix(String path); String separatorsToWindows(String path) 

请查看代码片段,查看相对路径,toString和分隔符更改:

 private String getRelativePathString(String volume, Path path) { Path volumePath = Paths.get(configuration.getPathForVolume(volume)); Path relativePath = volumePath.relativize(path); return FilenameUtils.separatorsToUnix(relativePath.toString()); } 

编写一个脚本,用一个正斜杠替换所有的“\\”,这个Java将转换成相应的操作系统路径。