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

问题描述 投票:5回答:3

我有一个屏幕,在按钮上单击我打开文件选择器,然后我选择一个名为“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作为我的文件名。请告诉我我的代码有什么问题。

java android file filechooser
3个回答
4
投票

需要从你的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

0
投票

尝试使用此方法:

 public String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

0
投票

这种方法在Kotlin中对我有用:

private fun getFilename(uri: Uri): String? {
    val cursor = activity?.contentResolver?.query(uri, null, null, null, null)
    var filename: String? = null

    cursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME)?.let { nameIndex ->
        cursor.moveToFirst()

        filename = cursor.getString(nameIndex)
        cursor.close()
    }

    return filename
}
© www.soinside.com 2019 - 2024. All rights reserved.