tru7
tru7

Reputation: 7212

Extract directory from a file path (Android Java)

I want to extract the directory part of a file path in Android. I know I can use

File file=new File(path);
String dir=file.getParent();

But I am not sure if this may introduce unnecessary overhead.Is there a more straight way?

Upvotes: 0

Views: 407

Answers (1)

Axel
Axel

Reputation: 14149

Ok, after your comment I get what you mean. Just look at the source (this is from OpenJDK, but I doubt Android will be too different). So, no overhead because of seeking or media access.

public String getParent() {
    int index = path.lastIndexOf(separatorChar);
    if (index < prefixLength) {
        if ((prefixLength > 0) && (path.length() > prefixLength))
            return path.substring(0, prefixLength);
        return null;
    }
    return path.substring(0, index);
}

Upvotes: 1

Related Questions