Juan Juan - 2 months ago 10
Android Question

Get the directory from a file path in java (android)

Is there a function to get the directory part of a file path?

so from

String a="/root/sdcard/Pictures/img0001.jpg";


you get

"/root/sdcard/Pictures"

Answer

Yes. First, construct a File representing the image path:

File file = new File(a);

If you're starting from a relative path:

file = new File(file.getAbsolutePath());

Then, get the parent:

String dir = file.getParent();

Or, if you want the directory as a File object,

File dirAsFile = file.getParentFile();
Comments