【问题标题】:Convert Windows style path into unix path in java code将 Windows 样式路径转换为 ​​java 代码中的 unix 路径
【发布时间】:2022-01-13 01:33:59
【问题描述】:

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

【问题讨论】:

    标签: java linux windows path path-separator


    【解决方案1】:

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

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

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

    请查看代码 sn-p,了解相对路径、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】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-08
          • 1970-01-01
          • 2010-10-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多