java - Android:所选文件的文件名不正确(来自文件选择器)

标签 java android file filechooser

我有一个屏幕,点击按钮打开一个文件选择器,然后我选择一个名为“Test.jpg”的文件进行进一步操作。 我使用以下代码获取该文件的名称。

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

这是调试器的结果

file.getName() => 167522

file.toString() => /external/images/media/167522

我想获取 Test.jpg 作为我的文件名。 请让我知道我的代码有什么问题。

最佳答案

需要来自您的 uri 的路径。这是从 uri 获取路径的方法。

public  String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

获取文件名

try{
  //call the getPath uri with context and uri
  //To get path from uri
  String path = getPath(this, uri);
  File file = new File(path);
  String filename = file.getName();
  Log.e(TAG, "File Name: " + filename);
}catch(Exception e){
   e("Err", e.toString()+"");
}

输出

uri: content://com.android.providers.media.documents/document/image%3A12876
FileName : profile.png

关于java - Android:所选文件的文件名不正确(来自文件选择器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45054005/

相关文章:

java - [GWT]是否可以在MouseOver 上选择menuItem?

java - 无法从Javadoc元素获取完全限定的类型名称

android - 包含许多 Activity 的滑动菜单

android - Android 上的 Mupdf 内存泄漏

java - Android 9.0 Pie 的 Picasso 图像加载问题

java - 如何很好地将 float 格式化为没有不必要的十进制 0 的字符串

java - 使用语音进行生物识别 - Android

c++ - 使用 ReadFile WinAPI 读取 'Binary' 文件

c++ - 帮助从文本文件 c++ 中读取每五行

file - 如何从文件更改中热加载结构