1

I have a java file that has some hard-coded path something like:

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 its creating META-INF with a \ and that is causing the build to fail.

How can I switch this to OS independent so that when the same is run on Linux it creates META-INF with correct path?

jww
  • 97,681
  • 90
  • 411
  • 885
Ashley
  • 1,447
  • 3
  • 26
  • 52
  • 1
    Possible duplicate of [Platform independent paths in Java](https://stackoverflow.com/q/3548775/608639), [How to load files on multiple platforms properly using Java?](https://stackoverflow.com/q/10594316/608639), [File path names for Windows and Linux](https://stackoverflow.com/q/20979625/608639), [Difference between File.separator and slash in paths](https://stackoverflow.com/q/2417485/608639), etc. – jww Jul 29 '19 at 23:44

1 Answers1

2

Instead of hardcoding separator \ or /, use File.separator

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

or event better do not use path literals at all but create Path object like

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

such Path object you can pass to the File constructor/utils but also you can always take String value of the path by calling toString() on the instance

m.antkowicz
  • 13,268
  • 18
  • 37