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

前端 未结 4 1630
无人及你
无人及你 2020-12-25 12:16

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

so from

String a=\"/root/sdcard/Pictures/img0001.jpg\";
相关标签:
4条回答
  • 2020-12-25 12:58

    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

    0 讨论(0)
  • 2020-12-25 12:59

    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
    0 讨论(0)
  • 2020-12-25 13:02

    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
    
    0 讨论(0)
  • 2020-12-25 13:06

    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();
    
    0 讨论(0)
提交回复
热议问题