Get the directory from a file path in java (androi

2020-02-23 07:10发布

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"

4条回答
Evening l夕情丶
2楼-- · 2020-02-23 07:26

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
查看更多
爷、活的狠高调
3楼-- · 2020-02-23 07:31

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

查看更多
4楼-- · 2020-02-23 07:36

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();
查看更多
家丑人穷心不美
5楼-- · 2020-02-23 07:48

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
查看更多
登录 后发表回答