Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 289
Laurent Grégoire Avatar asked Feb 20 '26 11:02

Laurent Grégoire


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("\\\\","/");

replaceAll takes a regular expression, which is why not just two backslashes are required in the first parameter. See https://stackoverflow.com/a/5596492.

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

like image 196
The Coding Penguin Avatar answered Feb 22 '26 00:02

The Coding Penguin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!