问题描述
我不认为这会是一项如此艰巨的任务,但我似乎无法在任何地方找到答案.在用户导航 android 设备上的文件夹并使用 .如:
I didn't think this would be such a difficult task to solve but I can't seem to find the answer anywhere. I'm trying to get the file path to an image after a user navigates the folders on an android device and selects the file using .Such as:
/documents/imagename.png
但是我尝试过的每个解决方案都会产生与此类似的字符串
But every solution I've tried results in a string similar to this
/documents/image:41879
首先是图片:41879"不是所选文件的名称和图像:"后面的数字每张图片都有变化,但正如你所看到的,这不是我想要的.我希望收到包含扩展名的完整文件路径.
First off "image:41879" is not the name of the selected file and the number after "image:" changes per picture, but as you can see this is not what I want. I'm looking to receive the full file path including the extension.
有人能帮忙吗?
当用户单击选择文件"时,我会运行此代码按钮
I have this code run when user clicks the "choose file" button
@Override
public void onClick(View v) {
// ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
// browser.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 10);
}
以下是我尝试过的许多解决方案之一,但无法如我所愿地获取文件路径
And below is one of the many solutions I've tried which does not obtain the file path as I want
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
TextView filename = (TextView) findViewById(R.id.filenameTextView);
Uri uri = data.getData();
String path = uri.getPath();
directory = path;
filename.setText(directory);
}
非常感谢任何和所有帮助.谢谢
Any and all help is greatly appreciated. Thank you
推荐答案
如果您想向用户显示文件路径并且它就像您的应用程序的核心功能一样,那么我真的很抱歉地说,从API 29 或 Android 10 出于某些安全原因,我们无法获得文件的实际路径,但如果情况并非如此,那么您可以使用
If do you want to display the File Path to the user and it's like a core feature of your app, then I'm really sorry to say that, from API 29 or Android 10 we can't get the actual path of the file dur to some security reasons but if that's not the case then you can do it with
InputStream is = getContentResolver().openInputStream(data.getData());
然后您可以使用 Cursor
传递 Intent 数据,然后使用 OpenableColumns.FILE_NAME
和 OpenableColumns 来获取文件名和文件大小.FILE_SIZE
.
Then you can get File Name and File Size using Cursor
passing the Intent data and then using OpenableColumns.FILE_NAME
and OpenableColumns.FILE_SIZE
.
这篇关于如何从android文件中获取真实的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!