[android] How to get file name from file path in android

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);
        } 

    }

}

This question is related to android android-camera android-sdcard

The answer is


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

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


We can find file name below code:

File file =new File(Path);
String filename=file.getName();

Other Way is:

String[] parts = selectedFilePath.split("/");
    final String fileName = parts[parts.length-1];

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


add this library

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

then call FilenameUtils class

   val getFileName = FilenameUtils.getName("Your File path")

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

String filename = uri.getLastPathSegment();

FilenameUtils to the rescue:

String filename = FilenameUtils.getName("/storage/sdcard0/DCIM/Camera/1414240995236.jpg");

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";
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-camera

Android camera android.hardware.Camera deprecated How to get file name from file path in android Android Camera Preview Stretched How to compress image size? Android open camera from button How to capture and save an image using custom camera in Android? Android Camera : data intent returns null How to measure height, width and distance of object using camera? Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab How to turn on front flash light programmatically in Android?

Examples related to android-sdcard

Android 6.0 Marshmallow. Cannot write to SD Card How to access /storage/emulated/0/ How to get file name from file path in android Android Open External Storage directory(sdcard) for storing file Android: How to open a specific folder via Intent and show its content in a file browser? Simple mediaplayer play mp3 from file path? error opening trace file: No such file or directory (2) How can I get the external SD card path for Android 4.0+? How do I adb pull ALL files of a folder present in SD Card Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?