add a trailing slash in path if not exists java

Java Feb 09, 2020 Viewed 159 Comments 0

Path separators are different on Windows and Linux. You can use the constant File.separatorChar. The system-dependent default name-separator character. This field is initialized to contain the first character of the value of the system property file.separator. On UNIX systems the value of this
field is '/'; on Microsoft Windows systems it is '\\'.

Get the last character of a string

String path = "/path/to/folder";
char last = path.charAt(path.length() - 1);

Appending a trailing slash if needed

String path = "/path/to/folder";
if (path.charAt(path.length() - 1) != File.separatorChar) {
    path += File.separator;
Updated Feb 09, 2020