如何在安卓系统中从文件路径中获取文件名

66

我想从SD卡文件路径中获取文件名。例如:/storage/sdcard0/DCIM/Camera/1414240995236.jpg,我想获取 1414240995236.jpg 的文件名。

我已经编写了提取代码,但它没有起作用。请帮忙。
以下是我的代码:

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

    }

}
13个回答

194

我认为你可以使用substring方法从路径字符串中获取文件名。

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

11
我认为你应该使用File.separator而不是"/"。 - android developer
1
无法工作,假设我的文件路径为“:/storage/sdcard0/DCIM/Camera/2014/04/03.jpg”,那么它会返回“03.jpg”,所以请尝试这个解决方案,它是100%有效的https://dev59.com/o18d5IYBdhLWcg3wpzr4#34435874。 - Ravi Makvana
5
@RvPanchal,你有什么问题吗?应返回文件名“03.jpg”。 - fatboy
@RvPanchal,那么你的解决方案与链接中的解决方案有什么不同?你的解决方案也会完全给出结果“03.jpg”。 - HendraWD
5
如果你的意思是“2014/04/03.jpg”应该是文件的名称,我认为我们不能把“/”作为文件名本身的字符。 - HendraWD

69

获取文件名的简单易用方法

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

添加这段代码并打印 strFileName,你将得到 strFileName = 1414240995236.jpg


54

@manimcaAndroidDeveloper 一定要通过点赞和接受我的答案来表示感谢(当计时器结束时)。 - Code-Apprentice
你理解这段代码吗?String CapturedImageDetails = imageUri.getLastPathSegment(); 我使用了这段代码。 - Manikandan K
我正在使用两种输出方式。1)SQLite数据库 2)PHP Web服务并使用MySQL。 - Manikandan K
@Code-Apprentice 如果文件名中有冒号(:)怎么办? - pratZ
@pratZ 你能给一个具体的例子吗?同时请确保阅读我提供的文档,看看它是否回答了你的问题。 - Code-Apprentice
显示剩余4条评论

9

FilenameUtils 来解救:

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

嗨,我的Android Studio显示“无法解析符号FilenameUtils”。 - most venerable sir
1
尊敬的先生,请查看以下链接以解决您的问题:https://dev59.com/mmMm5IYBdhLWcg3wFLw4#17897067 - Hardik Maru

6

假设您拥有绝对路径,Kotlin 中一行解决方案

File(currentPhotoPath).name

5
我们可以在以下代码中找到文件名:
File file =new File(Path);
String filename=file.getName();

3

最终的工作解决方案:

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

2

虽然这是一个老帖子,但我想更新一下;

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

更多信息可以在这里找到; Android文件类


0
你可以使用Common IO库,它可以获取文件的基本名称和扩展名。
 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

很不幸,在运行时,许多人都会遇到这个问题:"java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/commons/io/FilenameUtils;" - Alen Siljak

0

Kotlin已经提供了一个简单的解决方案:path.substringAfterLast("/")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接