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



我正在使用一个Java代码,该代码旨在在Windows上运行,并且包含大量使用Windows样式路径"System.getProperty("user.dir")\trash\blah的文件引用。我负责调整它并在 Linux 中部署。有没有一种有效的方法可以将所有这些路径(\)转换为Unix样式(/),例如"System.getProperty("user.dir")/trash/blah"。也许,java或linux中的某些配置使用\作为/。

我的方法是使用 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());
}

我重读了你的问题,意识到你可能不需要帮助编写路径。对于您要做的事情,我无法找到解决方案。当我最近在一个项目中执行此操作时,我不得不花时间转换所有路径。此外,我假设将"user.home"作为根目录相对确定地包含运行我的应用程序的用户的写入权限。无论如何,以下是我解决的一些路径问题。

我像这样重写了原始的Windows代码:

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

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

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

编写一个脚本,将所有"\\"替换为单个正斜杠,Java 会将其转换为受尊重的操作系统路径。

最新更新