【问题标题】:Fix Hardcoded Windows Paths in Java so that it works in linux also [duplicate]修复 Java 中的硬编码 Windows 路径,使其在 linux 中也能工作 [重复]
【发布时间】:2019-12-07 06:51:35
【问题描述】:

我有一个 java 文件,其中包含一些硬编码路径,例如:

public class ReportBuilder
{
  private static final String DIRECTORY = "META-INF";
  private static final String REPORT_HTML = "report.html";

  public static void createHTMLReport(String projectPath, String artifactName, ValidationResult result) throws MojoExecutionException {
    String directoryPath = projectPath + "\\" + "META-INF";
    String filePath = directoryPath + "\\" + "report.html";
  }
}

Linux 它使用\ 创建META-INF,这导致构建失败。

如何将其切换为独立于操作系统,以便在 Linux 上运行相同的程序时,它会创建具有正确路径的 META-INF

【问题讨论】:

标签: java linux operating-system


【解决方案1】:

使用File.separator代替硬编码分隔符\/

String filePath = directoryPath + File.separator + "report.html";

或者事件最好不要使用路径文字,而是创建Path 对象

Path filePath = Paths.get(directoryPath, "report.html");

这样的Path 对象,您可以传递给File 构造函数/实用程序,但您也可以始终通过在实例上调用toString() 来获取路径的字符串值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-31
    • 2016-01-20
    • 2022-10-14
    • 1970-01-01
    • 2021-02-23
    • 2021-05-20
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多