How to get file name from file path in android

后端 未结 10 2562
清歌不尽
清歌不尽 2020-12-08 06:13

I want to get file name from sdcard file path. e.g. :/storage/sdcard0/DCIM/Camera/1414240995236.jpg I want get 1414240995236.jpg I have written the code to fe

相关标签:
10条回答
  • 2020-12-08 06:58

    you can use the Common IO library which can get you the Base name of your file and the Extension.

     String fileUrl=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";
          String fileName=FilenameUtils.getBaseName(fileUrl);
               String    fileExtention=FilenameUtils.getExtension(fileUrl);
    //this will return filename:1414240995236 and fileExtention:jpg
    
    0 讨论(0)
  • 2020-12-08 06:59

    Old thread but thought I would update;

     File theFile = .......
     String theName = theFile.getName();  // Get the file name
     String thePath = theFile.getAbsolutePath(); // Get the full
    

    More info can be found here; Android File Class

    0 讨论(0)
  • 2020-12-08 07:00

    add this library

      implementation group: 'commons-io', name: 'commons-io', version: '2.6'
    

    then call FilenameUtils class

       val getFileName = FilenameUtils.getName("Your File path")
    
    0 讨论(0)
  • 2020-12-08 07:03

    Final working solution:

     public static String getFileName(Uri uri) {
        try {
            String path = uri.getLastPathSegment();
            return path != null ? path.substring(path.lastIndexOf("/") + 1) : "unknown";
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return "unknown";
    }
    
    0 讨论(0)
提交回复
热议问题