Search code examples
javafilepathextractfilenames

Extract basenames of multiple files from one path


Hello programmers!

I have some issue related with the filepath in Java.

Take a look at this path (in the real filepath there's no "{}" brackets, and NULL is real null mark):

\\server\directory\64956012.TIF{NULL}64956014.TIF{NULL}64956016.TIF{NULL}64956018.TIF% 

The question is:

is there some easy way to extract these filenames using i.e. Apache Commons? I don't need whole path (prefix) - I need only filenames.

Thank you in advance.


Solution

  • I assume the format is always the same have a first part with path info and ending with %.

    String s1 = "\\\\serverdirectory\\64956012.TIF\u000064956014.TIF\u000064956016.TIF\u000064956018.TIF%";
    String s2 = s1.substring(s1.lastIndexOf("\\") + 1, s1.length() - 1);
    String[] splitted = s2.split("\u0000");
    for (int i = 0; i < splitted.length; i++)
        System.out.println(splitted[i]);
    

    s2 contains only the list of filenames separated by the null byte (\u0000). The output of this code is:

    64956012.TIF
    64956014.TIF
    64956016.TIF
    64956018.TIF