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

Viewed 7246

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.

4 Answers

Building on the iterator idea (my problem is similar: need the path for a web page, but it has to be relative and start with a slash)

StringBuilder foo = new StringBuilder();
relative.iterator().forEachRemaining(part -> foo.append("/").append(part));

foo will contain the appropriate path.

Related