Make Java getAbsolutePath() return forward-slash on all machines

Viewed 1222

On Windows, File::getAbsolutePath() will return backward-slashes in paths; on UNIX, forward-slashes.

Since both versions are valid filenames on Windows machine, is it possible to force File::getAbsolutePath() (and associated functions) to always return the forward-slash version of a filename?

1 Answers

You could use a function like replaceAll() to replace any backward-slash in the path by forward-slashes. This would look like :

String oldPath = "path\\dzq\\dzqf";
String newPath = old.replaceAll("\\", "/");

More info on replaceAll() here : https://www.javatpoint.com/java-string-replaceall and here : https://howtodoinjava.com/java/string/java-string-replaceall-example/

The functions returning you the path always use the platform's default separator : https://www.journaldev.com/851/java-file-separator-separatorchar-pathseparator-pathseparatorchar

Related