2

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

4

3 回答 3

2

我的做法是使用 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());
}
于 2016-11-13T03:10:09.687 回答
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);
于 2014-11-18T01:22:22.373 回答
0

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

于 2014-11-18T01:38:38.647 回答