How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

I am using 3rd party file manager to pick a file (PDF in my case) from the file system.

This is how I launch the activity:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

String chooserName = getString(R.string.Browse);
Intent chooser = Intent.createChooser(intent, chooserName);

startActivityForResult(chooser, ActivityRequests.BROWSE);

This is what I have in onActivityResult:

Uri uri = data.getData();
if (uri != null) {
    if (uri.toString().startsWith("file:")) {
        fileName = uri.getPath();
    } else { // uri.startsWith("content:")

        Cursor c = getContentResolver().query(uri, null, null, null, null);

        if (c != null && c.moveToFirst()) {

            int id = c.getColumnIndex(Images.Media.DATA);
            if (id != -1) {
                fileName = c.getString(id);

Code snippet is borrowed from Open Intents File Manager instructions available here:

The purpose of if-else is backwards compatibility. I wonder if this is a best way to get the file name as I have found that other file managers return all kind of things. For example, Documents ToGo return something like the following:


on which getContentResolver().query() returns null. To make things more interesting, unnamed file manager (I got this URI from client log) returned something like:


Is there a preferred way of extracting the file name from URI or one should resort to string parsing? has nice example code for this:

A condensed version to just extract the file name (assuming "this" is an Activity):

public String getFileName(Uri uri) {
  String result = null;
  if (uri.getScheme().equals("content")) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    try {
      if (cursor != null && cursor.moveToFirst()) {
        result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
    } finally {
  if (result == null) {
    result = uri.getPath();
    int cut = result.lastIndexOf('/');
    if (cut != -1) {
      result = result.substring(cut + 1);
  return result;

I call startActivityForResult with Intent ACTION_GET_CONTENT. You can get file name from this code, or any other field by modifying the projection getContentResolver(); Cursor metaCursor = cr.query(uri, projection, null, null, null​); if getString(0); } } finally { metaCursor.close(); } } return path;. How to extract the file name from the file list? Now I have several files, their names include version number, I want to extract their file name only and strip the version number, ES File Explorer_3.0.5.5.apk ES Task Manager_1.4.1.apk Facebook_3.7.apk Gmail_4.6 (836823).apk Google+_4.1.2.51968121.a

I'm using something like this:

String scheme = uri.getScheme();
if (scheme.equals("file")) {
    fileName = uri.getLastPathSegment();
else if (scheme.equals("content")) {
    String[] proj = { MediaStore.Images.Media.TITLE };
    Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
    if (cursor != null && cursor.getCount() != 0) {
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE);
        fileName = cursor.getString(columnIndex);
    if (cursor != null) {

How to extract the file name from URI returned from Intent.​ACTION_GET_CONTENT? - android. How can I get the name of a file from a uri returned in OnActivityResult, I tried using this bit of code . Uri uri = data.getData(); String fileName = uri.getLastPathSegment(); but it just returns something like this images:3565. The file that is picked is not only of image type it can be a video, or document file, etc.

Taken from Retrieving File information | Android developers

Retrieving a File's name.
private String queryName(ContentResolver resolver, Uri uri) {
    Cursor returnCursor =
            resolver.query(uri, null, null, null, null);
    assert returnCursor != null;
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    String name = returnCursor.getString(nameIndex);
    return name;

Retrieve a file's MIME type; Retrieve a file's name and size app retrieves the MIME type of a file once the server app has returned the content URI to the client: Kotlin Java More /* * Get the file's content URI from the incoming Intent, then If the uri is a content provider uri, this is how you should retrieve file info. Cursor cursor = getContentResolver().query(uri, null, null, null, null); /* * Get the column indexes of the data in the Cursor, * move to the first row in the Cursor, get the data, * and display it.

If you want it short this should work.

Uri uri= data.getData();
File file= new File(uri.getPath());

ACTION_GET_CONTENT); intent. How to extract the file name from URI returned from Intent. setType(getString(R.string.app_pdf_mime_type)); intent. The accepted answer is problematic for http urls. Moreover Uri.LocalPath does Windows specific conversions, and as someone pointed out leaves query strings in there. A better way is to use Uri.AbsolutePath. The correct way to do this for http urls is: Uri uri = new Uri(hreflink); string filename = System.IO.Path.GetFileName(uri.AbsolutePath);

Easiest ways to get file name:

val fileName = File(uri.path).name
// or
val fileName = uri.pathSegments.last()

If they don't give you the right name you should use:

fun Uri.getName(context: Context): String {
    val returnCursor = context.contentResolver.query(this, null, null, null, null)
    val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
    val fileName = returnCursor.getString(nameIndex)
    return fileName

How to extract the file name from URI returned from Intent.​ACTION_GET_CONTENT? … Because from android KitKat ( sdk version 19 ), the system returned uri is not real local file path uri, it is a content provider style uri, so we should parse the uri and get the real file local path by query related content provider ( image provider, audio provider, video provider and document provider ).

if (cursor == null) { // Source is Dropbox or other similar local file path result = contentURI.getPath(); ACTION_GET_CONTENT into File. Uri filePathFromActivity = (Uri) extras.get(Intent. return new File(uri. copyFileToCache(context, intent, tempOutDir) ? null : "copyFileToCache() failed"; String filename = intent.getData()  A path may contain the drive name, directory name(s) and the filename. To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now we have a  150 How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT? 116 Interview Question: Merge two sorted singly linked lists without creating new nodes 92 What is the fastest way to view images from the terminal?

Cannot retrieve contributors at this time Added and modified to use isDocumentUri and getDocumentId methods with KITKAT target api ContentUris;. import android.content.Context;. import android.content.Intent; return file;. } else {. String filename = file.getName();. String filepath = file. ACTION_GET_CONTENT);. Retrieving file information. Contents. Retrieve a file's MIME type. Retrieve a file's name and size. Before a client app tries to work with a file for which it has a content URI, the app can request information about the file from the server app, including the file's data type and file size. The data type helps the client app to determine if it can handle the file, and the file size helps the client app set up buffering and caching for the file.

  • Same question with maybe better answer:…
  • in case when you attempt read mimeType or fileName of file from camera, firstly you have to notify MediaScanner that will convert URI of your just created file from file:// to content:// in onScanCompleted(String path, Uri uri) method
  • Adding new String[]{OpenableColumns.DISPLAY_NAME} as a second parameter to query will filter the columns for a more efficient request.
  • OpenableColumns.DISPLAY_NAME didn't work for me, i used MediaStore.Files.FileColumns.TITLE instead.
  • This will crash for videos when creating the cursor with a java.lang.IllegalArgumentException: Invalid column latitude unfortunately. Works perfectly for photos though!
  • I have run some tests on your code. On URI returned by OI File Manager IllegalArgumentException is thrown as column 'title' does not exist. On URI returened by Documents ToGo cursor is null. On URI returned by unknown file manager scheme is (obviously) null.
  • Hmm, interesting. Yeah, testing for scheme != null is a good idea. Actually I don't think TITLE is what you want. I was using that because certain media types in Android (like songs chosen through the music picker) have URIs like content://media/external/audio/media/78 and I wanted to display something more relevant than the ID number. You can simply use uri.getLastPathSegment() like my code uses for file:// URIs if you have a URI like content://...somefile.pdf
  • uri.getLastPathSegment(); - you have saved my day :)
  • @Ken Fehling: This didn't work for me. It works when I click a file in a file browser, but when I click on an email attachment, I still get the content://... thing. I tried all the suggestions here without luck. Any idea why?
  • Hi, why the cursor is not close()d?
  • I've been looking for this for way too long!
  • Thank you. Good lord why do they have to make such a trivial thing so annoying?
  • It only works with content files. See for full method