从URI中获取文件名的方法

17

你好,我正在开发基于Android gallery的视频播放器。我从gallery接收URI,并需要在播放视频时显示视频标题。因此,如果内容没有标题元数据,我需要显示视频文件名。如何获取视频内容文件名?

谢谢。


所以您想要显示URI?还是按/拆分它并显示最后一部分? - Mikhail
1
我想显示最后一部分。如果我显示URI值是/external/video/media/3。但是3是id,不是文件名。 - byungkyu
看看这篇其他的帖子:https://dev59.com/LnNA5IYBdhLWcg3wEZeT - Jaime Botero
谷歌的答案: https://developer.android.com/training/secure-file-sharing/retrieve-info.html - MechEthan
10个回答

28

以下是从url获取文件名的代码:

Uri u = Uri.parse("www.google.com/images/image.jpg");

File f = new File("" + u);

f.getName();

在我的情况下不起作用,它只返回URL末尾的名称,但是在从Google驱动器或其他地方获取文件中的文档时,它会返回最后一个正斜杠后面的字符串。 - cammando

10

由于没有一个答案真正解决了问题,我在这里放上我的解决方案,希望它能有所帮助。

     String fileName;
     if (uri.getScheme().equals("file")) {
            fileName = uri.getLastPathSegment();
        } else {
            Cursor cursor = null;
            try {
                cursor = getContentResolver().query(uri, new String[]{
                        MediaStore.Images.ImageColumns.DISPLAY_NAME
                }, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
                    Log.d(TAG, "name is " + fileName);
                }
            } finally {

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

5
如果URI是内容提供程序URI,则应按照以下方式检索文件信息。
        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.
         */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        cursor.moveToFirst();
        nameView.setText(cursor.getString(nameIndex));

https://developer.android.com/training/secure-file-sharing/retrieve-info.html


这怎么可能是API呢?看起来我们好像在试图逆向工程某个对象。 - topher217

4
对于 Kotlin,只需简单地:
val fileName = File(uri.path).name

这真的是Kotlin特定的吗?我认为这也适用于相应的Java语法,对吗?我还认为,关于URI的"性质"还有一些附加条件。但无论如何,对我来说这是最简单的解决方案。 - undefined

2

以下代码适用于我从图库中选择图片的情况,它应该适用于任何文件类型。

    String fileName = "default_file_name";
    Cursor returnCursor =
            getContentResolver().query(YourFileUri, null, null, null, null);
    try {
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        returnCursor.moveToFirst(); 
        fileName = returnCursor.getString(nameIndex);
        LOG.debug(TAG, "file name : " + fileName);
    }catch (Exception e){
        LOG.error(TAG, "error: ", e);
        //handle the failure cases here
    } finally {
        returnCursor.close();
    }

这里,您可以找到详细的解释和更多信息。

1
try
        {
            String uriString = "http://somesite.com/video.mp4";
            URI uri = new URI(uriString);

            URL videoUrl = uri.toURL();
            File tempFile = new File(videoUrl.getFile());
            String fileName = tempFile.getName();
        }
        catch (Exception e)
        {

        }

有人给这个答案点了踩,请问您能解释一下为什么吗? - Ayaz Alifov
@Grsmto,抱歉,您在写评论之前是否尝试运行代码?我认为没有,因为我刚刚检查了您的示例URL,并返回了正确的结果- file.mp3。 - Ayaz Alifov
我可能错了,意识到我的Android Studio调试器表现得非常奇怪...有一些旧的缓存以前的构建等等...我会删除我的答案。 - adriendenat

1
int actual_image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
String filename = cursor.getString(actual_image_column_index);

这是一个关于图片的示例。你可以根据自己的需求尝试同样的方法(比如视频)。

谢谢,祝你好运 :)


0

谷歌参考:

https://developer.android.com/training/secure-file-sharing/retrieve-info#RetrieveFileInfo

        /*
         * Get the file's content URI from the incoming Intent,
         * then query the server app to get the file's display name
         * and size.
         */
        Uri returnUri = returnIntent.getData();
        Cursor returnCursor =
                getContentResolver().query(returnUri, 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.
         */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        TextView nameView = (TextView) findViewById(R.id.filename_text);
        TextView sizeView = (TextView) findViewById(R.id.filesize_text);
        nameView.setText(returnCursor.getString(nameIndex));
        sizeView.setText(Long.toString(returnCursor.getLong(sizeIndex)));

0
尝试下面的代码,
    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 {
                cursor.close();
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }

-2

这里给你一个示例代码,可以从相册上传图片

要提取文件名/图片名,请按照以下步骤操作

File f = new File(selectedPath);
System.out.println("Image name is   ::" + f.getName());//get name of file

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == YourActivity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String selectedPath = getPath(selectedImageUri);
File f = new File(selectedPath);
System.out.println("Image name is   ::" + f.getName());//get name of file
}
}

希望这能有所帮助


3
getPath() 是一个自定义函数,在你的代码片段中没有列出。 - sweisgerber.dev

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