在Windows代码中将Windows样式路径转换为unix路径

时间:2014-11-18 01:06:26

标签: java linux windows path path-separator

我正在使用设计为在Windows上运行的java代码,并使用Windows样式路径“System.getProperty(”user.dir“)\ trash \ blah”包含大量文件引用。我负责调整它并在linux中部署。是否有一种有效的方法将所有这些路径(\)转换为unix样式(/),如“System.getProperty(”user.dir“)/ trash / blah”。也许,java或linux中的一些配置使用\ as /.

3 个答案:

答案 0 :(得分:1)

我重新阅读了您的问题,并意识到您可能不需要帮助编写路径。对于您尝试做的事情,我无法找到解决方案。当我最近在一个项目中这样做时,我不得不花时间转换所有路径。此外,我假设在" 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);

答案 1 :(得分:1)

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

为了转换路径分隔符,我更喜欢使用apache common io库的FilenameUtils。它提供了三个usefule函数:

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());
}

答案 2 :(得分:0)

编写一个脚本,用一个正斜杠替换所有“\\”,Java将转换为受尊重的OS路径。

相关问题