How to split directory path components in string in java

directory, file, java, split, string

Solution

I'd rather not succumb to the temptation of using split ona file name, when java has its own cleaner, cross-platform functions for path manipluation.

I think this basic pattern works from java 1.4 and onward:

    File f = new File("c:\\Some\\Folder with spaces\\Or\\Other");
    do {
        System.out.println("Parent=" + f.getName());
        f = f.getParentFile();
    } while (f.getParentFile() != null);
    System.out.println("Root=" + f.getPath());

Will output:

    Path=Other
    Path=Or
    Path=Folder with spaces
    Path=Some
    Root=c:\

You probably want to use f.getCanonicalPath or f.getAbsolutePath first, so it also works with relative paths.

Unfortunately, this needs f.getPath for the root and f.getName for the other parts, and i create the parts in backward order.

UPDATE: You can compare f with fsv.getHomeDirectory() while scanning upward, and break when it turns out you were in a subdirectory of your home folder.

Problem

Possible Duplicate: how to split the string in java ``` FileSystemView fsv = FileSystemView.getFileSystemView(); File[] roots = fsv.getRoots(); for (int i = 0; i < roots.length; i++) { System.out.println("Root: " + roots[i]); } System.out.println("Home directory: " + fsv.getHomeDirectory()); ``` Root: C:\Users\RS\Desktop Home directory: C:\Users\RS\Desktop I want cut the root or Home Directory components like String C, Users, RS, Desktop

Original source

Related problems