How to get file name from file path in android
Asked Answered
R

13

66

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 fetch the same but it is not working. Please help.
Below is my code:

@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data)
{
    if ( requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

        if ( resultCode == RESULT_OK) {

            /*********** Load Captured Image And Data Start ****************/

            String imageId = convertImageUriToFile( imageUri,CameraActivity);


            //  Create and excecute AsyncTask to load capture image

            new LoadImagesFromSDCard().execute(""+imageId);

            /*********** Load Captured Image And Data End ****************/


        } else if ( resultCode == RESULT_CANCELED) {

            Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
        } else {

            Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
        }
    }
}


/************ Convert Image Uri path to physical path **************/

public static String convertImageUriToFile ( Uri imageUri, Activity activity )  {

    Cursor cursor = null;
    int imageID = 0;

    try {

        /*********** Which columns values want to get *******/
        String [] proj={
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media._ID,
                MediaStore.Images.Thumbnails._ID,
                MediaStore.Images.ImageColumns.ORIENTATION
        };

        cursor = activity.managedQuery(

                imageUri,         //  Get data for specific image URI
                proj,             //  Which columns to return
                null,             //  WHERE clause; which rows to return (all rows)
                null,             //  WHERE clause selection arguments (none)
                null              //  Order-by clause (ascending by name)

                );

        //  Get Query Data

        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
        int columnIndexThumb = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
        int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        //int orientation_ColumnIndex = cursor.
        //    getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);

        int size = cursor.getCount();

        /*******  If size is 0, there are no images on the SD Card. *****/

        if (size == 0) {


            imageDetails.setText("No Image");
        }
        else
        {

            int thumbID = 0;
            if (cursor.moveToFirst()) {

                /**************** Captured image details ************/

                /*****  Used to show image on view in LoadImagesFromSDCard class ******/
                imageID     = cursor.getInt(columnIndex);

                thumbID     = cursor.getInt(columnIndexThumb);

                String Path = cursor.getString(file_ColumnIndex);

                //String orientation =  cursor.getString(orientation_ColumnIndex);

                String CapturedImageDetails = " CapturedImageDetails : \n\n"
                        +" ImageID :"+imageID+"\n"
                        +" ThumbID :"+thumbID+"\n"
                        +" Path :"+Path+"\n";
                full_path_name=Path;



       //this is my path  
       //Path :/storage/sdcard0/DCIM/Camera/1414240995236.jpg  i want get 1414240995236.jpg








                // Show Captured Image detail on activity
                imageDetails.setText(Path);

            }
        }   
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Return Captured Image ImageID ( By this ImageID Image will load from sdcard )

    return ""+imageID;
}


/**
 * Async task for loading the images from the SD card.
 *
 * @author Android Example
 *
 */

// Class with extends AsyncTask class

public class LoadImagesFromSDCard  extends AsyncTask<String, Void, Void> {

    private ProgressDialog Dialog = new ProgressDialog(CameraPhotoCapture.this);

    Bitmap mBitmap;

    protected void onPreExecute() {
        /****** NOTE: You can call UI Element here. *****/

        // Progress Dialog
        Dialog.setMessage(" Loading image from Sdcard..");
        Dialog.show();
    }


    // Call after onPreExecute method
    protected Void doInBackground(String... urls) {

        Bitmap bitmap = null;
        Bitmap newBitmap = null;
        Uri uri = null;      


        try {

            /**  Uri.withAppendedPath Method Description
             * Parameters
             *    baseUri  Uri to append path segment to
             *    pathSegment  encoded path segment to append
             * Returns
             *    a new Uri based on baseUri with the given segment appended to the path
             */

            uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + urls[0]);

            /**************  Decode an input stream into a bitmap. *********/
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

            if (bitmap != null) {

                /********* Creates a new bitmap, scaled from an existing bitmap. ***********/

                newBitmap = Bitmap.createScaledBitmap(bitmap, 170, 170, true);

                bitmap.recycle();

                if (newBitmap != null) {

                    mBitmap = newBitmap;
                }
            }
        } catch (IOException e) {
            // Error fetching image, try to recover

            /********* Cancel execution of this task. **********/
            cancel(true);
        }

        return null;
    }


    protected void onPostExecute(Void unused) {

        // NOTE: You can call UI Element here.

        // Close progress dialog
        Dialog.dismiss();

        if(mBitmap != null)
        {
            // Set Image to ImageView 

            showImg.setImageBitmap(mBitmap);
        } 

    }

}
Runofthemill answered 26/10, 2014 at 5:28 Comment(0)
T
195

I think you can use substring method to get name of the file from the path string.

String path=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg"; 
// it contains your image path...I'm using a temp string...
String filename=path.substring(path.lastIndexOf("/")+1);
Tonnage answered 26/10, 2014 at 6:11 Comment(4)
I think you should use File.separator instead of "/"Belabor
@RvPanchal whats your problem? it should return file name "03.jpg"Tonnage
@RvPanchal So what is the different with your solution from the link? Your solution will exactly give result "03.jpg" too.Rickart
If you mean that "2014/04/03.jpg" should be the name of the file. I don't think that we can put "/" as a character on the file name itselfRickart
U
69

Simple and easy way to get File name

File file = new File("/storage/sdcard0/DCIM/Camera/1414240995236.jpg"); 
String strFileName = file.getName();

After add this code and print strFileName you will get strFileName = 1414240995236.jpg

Unnerve answered 23/12, 2015 at 12:36 Comment(0)
D
54

The easiest solution is to use Uri.getLastPathSegment():

String filename = uri.getLastPathSegment();
Dip answered 26/10, 2014 at 5:34 Comment(9)
@manimcaAndroidDeveloper Be sure to show your thanks with an upvote and accepting my answer (when the timer runs out).Dip
ya sure. but i can't get file name. i got answer like this. /storage/sdcard/DCIM/Camera/1414302043784.jpgRunofthemill
@manimcaAndroidDeveloper What is the exact code that gives that result?Dip
String CapturedImageDetails = imageUri.getLastPathSegment(); im used this code. do you understand?Runofthemill
@manimcaAndroidDeveloper And how do you see the value of this CapturedImageDetails?Dip
i am using two way of output. 1) sqlite database 2) php webservice and using my sql.Runofthemill
@manimcaAndroidDeveloper What is the exact code that produces the output?Dip
@Dip what if the file name has : (colon)Fredel
@Fredel Can you give a specific example? Also be sure to read the docs I linked to see if it answers your question.Dip
N
9

FilenameUtils to the rescue:

String filename = FilenameUtils.getName("/storage/sdcard0/DCIM/Camera/1414240995236.jpg");
Nanceynanchang answered 8/9, 2016 at 10:58 Comment(2)
Hi, my android studio says"cannot resolve symbol FilenameUtils".Halla
@mostvenerablesir Please check this link for your issue: https://mcmap.net/q/94907/-add-commons-io-dependency-to-gradle-project-in-android-studioThornberry
L
6

One liner solution in kotlin assuming you have the absolute path

File(currentPhotoPath).name
Logician answered 5/10, 2021 at 13:26 Comment(0)
R
5

We can find file name below code:

File file =new File(Path);
String filename=file.getName();
Raindrop answered 20/2, 2018 at 6:56 Comment(0)
C
3

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";
}
Cheffetz answered 17/5, 2019 at 13:25 Comment(0)
G
2

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

Gebhardt answered 4/5, 2016 at 10:8 Comment(0)
U
0

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
Undistinguished answered 29/9, 2015 at 3:52 Comment(1)
Unfortunately, during runtime many people are getting this: "java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/commons/io/FilenameUtils;"Receivership
D
0

Other Way is:

String[] parts = selectedFilePath.split("/");
    final String fileName = parts[parts.length-1];
Demythologize answered 19/1, 2019 at 5:0 Comment(0)
C
0

add this library

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

then call FilenameUtils class

   val getFileName = FilenameUtils.getName("Your File path")
Catie answered 18/11, 2020 at 8:53 Comment(1)
Using such a "fat" library for such simple task is not the best ideaMoneylender
G
0

In kotlin:

fileUrl.split("/").last()

Garish answered 16/5, 2022 at 15:21 Comment(0)
A
0

Kotlin provides a simple solution already path.substringAfterLast("/")

Anlage answered 25/4, 2023 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.