Convert String with paths denoted with dot into a filename

file, java, string

Solution

Use `String.replaceAll(regex, replacement)` with the right regex:

String filename = value.replaceAll("\\.(?=.*\\.)", "/");

This regex matches dots, but only if there's another dot somewhere after the matched dot, checked using a "look ahead", which has syntax `(?=regex)`.

Here's a test:

public static void main(String[] args) {
    String value = "com.some.that.file.txt";
    String filename = value.replaceAll("\\.(?=.*\\.)", "/");
    System.out.println(filename);
}

Output:

com/some/that/file.txt

Edited:

To find the directory names, use this:

String dirname = filename.replaceAll("/(?!.*/).*", "");

or in one line:

String dirname = value.replaceAll("\\.(?=.*\\.)", "/").replaceAll("/(?!.*/).*", "");

This extra step uses a "negative look ahead", which has syntax `(?!regex)`, to match a slash only if there isn't a slash somewhere after the matched slash and then the regex matches everything after that using `.*`

Problem

I have a properties file ``` {Content} com.some.that.file.txt = com.some.dest com.fold.cust.dir = com.some.dest ``` Where the key denotes the name of a directory to copy to {Value}=com.some.dest I have replaced dots with "/" but with this i cannot retain the filename e.g file.txt becomes file/txt.

Original source