34

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"
Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
tru7
  • 6,348
  • 5
  • 35
  • 59

4 Answers4

69

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();
nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • 3
    If you're using a relative path like `File f = new File("file.txt");` be aware that `f.getParent()` will return `null`, not the parent – yate Feb 18 '15 at 21:35
  • How to extract path till "/root/sdcard/" or "/root/internal/" from file name ? – SimpleCoder Jul 14 '16 at 18:32
  • @hexafraction, JUST POSTED A QUESTION http://stackoverflow.com/questions/38381871/get-root-directory-i-e-external-or-external-sdcard-from-file-path – SimpleCoder Jul 14 '16 at 18:43
12

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

user370305
  • 108,599
  • 23
  • 164
  • 151
3

You could also use FilenameUtils from Apache. It provides you at least the following features for the example C:\dev\project\file.txt:

  • the prefix - C:\
  • the path - dev\project\
  • the full path - C:\dev\project\
  • the name - file.txt
  • the base name - file
  • the extension - txt
winterDroid
  • 91
  • 1
  • 2
0

I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):

  1. Use path for internal storage String path="/storage/sdcard0/myfile.txt";
  2. path="/storage/sdcard1/myfile.txt";
  3. mention permissions in Manifest file.

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

  4. First check file length for confirmation.
  5. Check paths in ES File Explorer regarding sdcard0 & sdcard1 is this same or else......

e.g.

File file=new File(path);
long=file.length();//in Bytes
Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
Mahadev Mane
  • 810
  • 8
  • 11