我正在使用第三方文件管理器从文件系统中选择一个文件(在我的情况下为PDF)。
这是我启动活动的方式:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(getString(R.string.app_pdf_mime_type));
intent.addCategory(Intent.CATEGORY_OPENABLE);
String chooserName = getString(R.string.Browse);
Intent chooser = Intent.createChooser(intent, chooserName);
startActivityForResult(chooser, ActivityRequests.BROWSE);
这就是我在onActivityResult
中所拥有的:
Uri uri = data.getData();
if (uri != null) {
if (uri.toString().startsWith("file:")) {
fileName = uri.getPath();
} else { // uri.startsWith("content:")
Cursor c = getContentResolver().query(uri, null, null, null, null);
if (c != null && c.moveToFirst()) {
int id = c.getColumnIndex(Images.Media.DATA);
if (id != -1) {
fileName = c.getString(id);
}
}
}
}
代码片段借用于此处提供的 Open Intents文件管理器说明:
http://www.openintents.org/en/node/829
if-else
的目的是向后兼容。我想知道这是否是获取文件名的最佳方式,因为我发现其他文件管理器会返回所有类型的东西
例如, Documents ToGo 返回如下内容:
content://com.dataviz.dxtg.documentprovider/document/file%3A%2F%2F%2Fsdcard%2Fdropbox%2FTransfer%2Fconsent.pdf
getContentResolver().query()
返回null
为了使事情更有趣,未命名的文件管理器(我从客户端日志中获取此URI)返回类似于:
/./sdcard/downloads/.bin
是否有从URI中提取文件名的首选方法,或者应该求助于字符串解析?
答案 0 :(得分:110)
developer.android.com有很好的示例代码: https://developer.android.com/guide/topics/providers/document-provider.html
只提取文件名的精简版(假设"此"是一个活动):
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;
}
答案 1 :(得分:41)
我正在使用这样的东西:
String scheme = uri.getScheme();
if (scheme.equals("file")) {
fileName = uri.getLastPathSegment();
}
else if (scheme.equals("content")) {
String[] proj = { MediaStore.Images.Media.TITLE };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE);
cursor.moveToFirst();
fileName = cursor.getString(columnIndex);
}
if (cursor != null) {
cursor.close();
}
}
答案 2 :(得分:27)
取自Retrieving File information | Android developers
private String queryName(ContentResolver resolver, Uri uri) {
Cursor returnCursor =
resolver.query(uri, null, null, null, null);
assert returnCursor != null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
returnCursor.close();
return name;
}
答案 3 :(得分:10)
如果你想要它很短,这应该有用。
Uri uri= data.getData();
File file= new File(uri.getPath());
file.getName();
答案 4 :(得分:7)
最简洁的版本:
public String getNameFromURI(Uri uri) {
Cursor c = getContentResolver().query(uri, null, null, null, null);
c.moveToFirst();
return c.getString(c.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
答案 5 :(得分:7)
获取文件名的最简单方法:
val fileName = File(uri.path).name
// or
val fileName = uri.pathSegments.last()
如果他们没有给你正确的名字,你应该使用:
fun Uri.getName(context: Context): String {
val returnCursor = context.contentResolver.query(this, null, null, null, null)
val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
returnCursor.moveToFirst()
val fileName = returnCursor.getString(nameIndex)
returnCursor.close()
return fileName
}
答案 6 :(得分:7)
我使用下面的代码来获取文件名称&我项目中Uri的文件大小。
/**
* Used to get file detail from uri.
* <p>
* 1. Used to get file detail (name & size) from uri.
* 2. Getting file details from uri is different for different uri scheme,
* 2.a. For "File Uri Scheme" - We will get file from uri & then get its details.
* 2.b. For "Content Uri Scheme" - We will get the file details by querying content resolver.
*
* @param uri Uri.
* @return file detail.
*/
public static FileDetail getFileDetailFromUri(final Context context, final Uri uri) {
FileDetail fileDetail = null;
if (uri != null) {
fileDetail = new FileDetail();
// File Scheme.
if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
File file = new File(uri.getPath());
fileDetail.fileName = file.getName();
fileDetail.fileSize = file.length();
}
// Content Scheme.
else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Cursor returnCursor =
context.getContentResolver().query(uri, null, null, null, null);
if (returnCursor != null && returnCursor.moveToFirst()) {
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
fileDetail.fileName = returnCursor.getString(nameIndex);
fileDetail.fileSize = returnCursor.getLong(sizeIndex);
returnCursor.close();
}
}
}
return fileDetail;
}
/**
* File Detail.
* <p>
* 1. Model used to hold file details.
*/
public static class FileDetail {
// fileSize.
public String fileName;
// fileSize in bytes.
public long fileSize;
/**
* Constructor.
*/
public FileDetail() {
}
}
答案 7 :(得分:4)
public String getFilename()
{
/* Intent intent = getIntent();
String name = intent.getData().getLastPathSegment();
return name;*/
Uri uri=getIntent().getData();
String fileName = null;
Context context=getApplicationContext();
String scheme = uri.getScheme();
if (scheme.equals("file")) {
fileName = uri.getLastPathSegment();
}
else if (scheme.equals("content")) {
String[] proj = { MediaStore.Video.Media.TITLE };
Uri contentUri = null;
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE);
cursor.moveToFirst();
fileName = cursor.getString(columnIndex);
}
}
return fileName;
}
答案 8 :(得分:2)
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(collectionView.frame.size.width/2.0, collectionView.frame.size.height/2.0);
}
答案 9 :(得分:1)
首先,您需要将URI
对象转换为URL
对象,然后使用File
对象检索文件名:
try
{
URL videoUrl = uri.toURL();
File tempFile = new File(videoUrl.getFile());
String fileName = tempFile.getName();
}
catch (Exception e)
{
}
就是这样,很容易。
答案 10 :(得分:1)
我的答案版本与@Stefan Haustein非常相似。我在Android Developer页面Retrieving File Information找到了答案;此处的信息比Storage Access Framework指南网站上的特定主题更加浓缩。在查询结果中,包含文件名的列索引为OpenableColumns.DISPLAY_NAME
。列索引的其他答案/解决方案都不适用于我。以下是示例函数:
/**
* @param uri uri of file.
* @param contentResolver access to server app.
* @return the name of the file.
*/
def extractFileName(uri: Uri, contentResolver: ContentResolver): Option[String] = {
var fileName: Option[String] = None
if (uri.getScheme.equals("file")) {
fileName = Option(uri.getLastPathSegment)
} else if (uri.getScheme.equals("content")) {
var cursor: Cursor = null
try {
// Query the server app to get the file's display name and size.
cursor = contentResolver.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.
if (cursor != null && cursor.moveToFirst()) {
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
fileName = Option(cursor.getString(nameIndex))
}
} finally {
if (cursor != null) {
cursor.close()
}
}
}
fileName
}
答案 11 :(得分:1)
xamarin / c#的Stefan Haustein函数:
public string GetFilenameFromURI(Android.Net.Uri uri)
{
string result = null;
if (uri.Scheme == "content")
{
using (var cursor = Application.Context.ContentResolver.Query(uri, null, null, null, null))
{
try
{
if (cursor != null && cursor.MoveToFirst())
{
result = cursor.GetString(cursor.GetColumnIndex(OpenableColumns.DisplayName));
}
}
finally
{
cursor.Close();
}
}
}
if (result == null)
{
result = uri.Path;
int cut = result.LastIndexOf('/');
if (cut != -1)
{
result = result.Substring(cut + 1);
}
}
return result;
}
答案 12 :(得分:1)
如果要使用扩展名的文件名,可以使用此功能获取。 它还适用于Google驱动器文件选择
public static String getFileName(Uri uri) {
String result;
//if uri is content
if (uri.getScheme() != null && uri.getScheme().equals("content")) {
Cursor cursor = global.getInstance().context.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
//local filesystem
int index = cursor.getColumnIndex("_data");
if(index == -1)
//google drive
index = cursor.getColumnIndex("_display_name");
result = cursor.getString(index);
if(result != null)
uri = Uri.parse(result);
else
return null;
}
} finally {
cursor.close();
}
}
result = uri.getPath();
//get filename + ext of path
int cut = result.lastIndexOf('/');
if (cut != -1)
result = result.substring(cut + 1);
return result;
}
答案 13 :(得分:0)
这实际上对我有用:
private String uri2filename() {
String ret;
String scheme = uri.getScheme();
if (scheme.equals("file")) {
ret = uri.getLastPathSegment();
}
else if (scheme.equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
ret = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
}
return ret;
}
答案 14 :(得分:0)
对于Kotlin,您可以使用类似这样的内容:
object FileUtils {
fun getFileName(context: Context, uri : Uri) : String {
var fileName = "Unknown"
when (uri.scheme) {
ContentResolver.SCHEME_FILE -> {
fileName = File(uri.path).name
}
ContentResolver.SCHEME_CONTENT -> {
try {
context.contentResolver.query(
uri,
null,
null,
null,
null
)?.apply {
if (moveToFirst()) {
fileName = getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
}
close()
}
} catch (e : Exception) {
return fileName
}
}
}
return fileName
}
}
答案 15 :(得分:0)
请尝试:
private String displayName(Uri uri) {
Cursor mCursor =
getApplicationContext().getContentResolver().query(uri, null, null, null, null);
int indexedname = mCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
mCursor.moveToFirst();
String filename = mCursor.getString(indexedname);
mCursor.close();
return filename;
}
答案 16 :(得分:0)
在阅读完此处给出的所有答案以及一些Airgram在其SDK中所做的工作后,我得出的结论是-我在Github上开源了该实用程序:
https://github.com/mankum93/UriUtilsAndroid/tree/master/app/src/main/java/com/androiduriutils
就像调用UriUtils.getDisplayNameSize()
一样简单。它提供了内容的名称和大小。
注意:仅适用于内容:// Uri
这里是代码的一瞥:
/**
* References:
* - https://www.programcreek.com/java-api-examples/?code=MLNO/airgram/airgram-master/TMessagesProj/src/main/java/ir/hamzad/telegram/MediaController.java
* - https://stackoverflow.com/questions/5568874/how-to-extract-the-file-name-from-uri-returned-from-intent-action-get-content
*
* @author Manish@bit.ly/2HjxA0C
* Created on: 03-07-2020
*/
public final class UriUtils {
public static final int CONTENT_SIZE_INVALID = -1;
/**
* @param context context
* @param contentUri content Uri, i.e, of the scheme <code>content://</code>
* @return The Display name and size for content. In case of non-determination, display name
* would be null and content size would be {@link #CONTENT_SIZE_INVALID}
*/
@NonNull
public static DisplayNameAndSize getDisplayNameSize(@NonNull Context context, @NonNull Uri contentUri){
final String scheme = contentUri.getScheme();
if(scheme == null || !scheme.equals(ContentResolver.SCHEME_CONTENT)){
throw new RuntimeException("Only scheme content:// is accepted");
}
final DisplayNameAndSize displayNameAndSize = new DisplayNameAndSize();
displayNameAndSize.size = CONTENT_SIZE_INVALID;
String[] projection = new String[]{MediaStore.Images.Media.DATA, OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};
Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
// Try extracting content size
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
if (sizeIndex != -1) {
displayNameAndSize.size = cursor.getLong(sizeIndex);
}
// Try extracting display name
String name = null;
// Strategy: The column name is NOT guaranteed to be indexed by DISPLAY_NAME
// so, we try two methods
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (nameIndex != -1) {
name = cursor.getString(nameIndex);
}
if (nameIndex == -1 || name == null) {
nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
if (nameIndex != -1) {
name = cursor.getString(nameIndex);
}
}
displayNameAndSize.displayName = name;
}
}
finally {
if(cursor != null){
cursor.close();
}
}
// We tried querying the ContentResolver...didn't work out
// Try extracting the last path segment
if(displayNameAndSize.displayName == null){
displayNameAndSize.displayName = contentUri.getLastPathSegment();
}
return displayNameAndSize;
}
}
答案 17 :(得分:0)
这将从不带文件扩展名的 Uri 返回文件名。
fun Uri.getFileName(): String? {
return this.path?.let { path -> File(path).name }
}
Here 我描述了一种获取带有扩展名的文件名的方法。
答案 18 :(得分:-1)
我从开发者官网找到了一些信息
我从开发者的网站上得到了一些信息
取得游标
val cursor = context.contentResolver.query(fileUri, null, null, null, null)
然后就可以获取姓名和文件大小
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
cursor.moveToFirst()
val fileName = cursor.getString(nameIndex)
val size = cursor.getLong(sizeIndex)
别忘记关闭资源
不要忘记关闭资源