Get the directory from a file path in java (android)
Solution 1
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();
Solution 2
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
Solution 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
tru7
I write code currently on C++ on the Qt platform for Windows / Mac / Android and Javascript/Typescript (node & browser) Also some backend stuff with PHP + MySql on Ubuntu (cloud server) On spare time some programming on music (MIDI, music learning support and tracking) On really spare time, learning guitar, jazz/classical with a touch of flamenco.
Updated on September 12, 2020Comments
-
tru7 over 3 years
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"