Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 591
tru7 Avatar asked Feb 18 '15 21:02

tru7


People also ask

How to get file object from path in java?

The method java. io. File. getAbsoluteFile() is used to get the File object with the absolute path for the directory or file.

How to give Absolute file path in java?

io. File. getAbsolutePath() is used to obtain the absolute path of a file in the form of a string. This method requires no parameters.


2 Answers

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();
like image 126
nanofarad Avatar answered Oct 19 '22 17:10

nanofarad


A better way, use getParent() from File Class..

String a="/root/sdcard/Pictures/img0001.jpg"; // A valid file path 
File file = new File(a); 
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null

http://developer.android.com/reference/java/io/File.html#getParent%28%29

like image 12
user370305 Avatar answered Oct 19 '22 15:10

user370305