javafilescalarelative-pathpath-separator

Java's File.toString or Path.toString with a specific path separator


I am developing a Scala application on Windows, and I need to insert a path to a file into an HTML template. I use Java's io and nio to work with files and paths.

/* The paths actually come from the environment. */
val includesPath = Paths.get("foo\\inc")
val destinationPath = Paths.get("bar\\dest")

/* relativeIncludesPath.toString == "..\\foo\\inc", as expected */
val relativeIncludesPath = destinationPath.relativize(includesPath)

The problem is that the output of relativeIncludesPath.toString contains backslashes \ as separators - because the application runs on Windows - but since the path is to be inserted into a HTML template, it must contain forward slashes / instead.

Since I couldn't find anything like file/path.toStringUsingSeparator('/') in the docs, I am currently helping myself with relativeIncludesPath.toString.replace('\\', '/'), which I find rather unappealing.

Question: Is there really no better way than using replace?

I also experimented with Java's URI, but it's relativize is incomplete.


Solution

  • The Windows implementation of the Path interface stores the path internally as a string (at least in the OpenJDK implementation) and simply returns that representation when toString() is called. This means that no computation is involved and there is no chance to "configure" any path separator.

    For this reason, I conclude that your solution is the currently the best option to solve your problem.