在Android中获取Uri的文件扩展名

时间:2017-04-12 10:01:57

标签: android

我想从手机查看所选文件的扩展名。 当我选择时,我得到:content://com.android.providers.media.documents/document/image%3A20247 我获取扩展的方法返回null:

 public static String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }

任何想法为什么?

2 个答案:

答案 0 :(得分:0)

尝试使用它,它对我有用

public static String getAbsolutePath(final Context context, final Uri uri) {

final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
    // ExternalStorageProvider
    if (isExternalStorageDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        if ("primary".equalsIgnoreCase(type)) {
            return Environment.getExternalStorageDirectory() + "/" + split[1];
        }

        // TODO handle non-primary volumes
    }
    // DownloadsProvider
    else if (isDownloadsDocument(uri)) {

        final String id = DocumentsContract.getDocumentId(uri);
        final Uri contentUri = ContentUris.withAppendedId(
                Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

        return getDataColumn(context, contentUri, null, null);
    }
    // MediaProvider
    else if (isMediaDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        Uri contentUri = null;
        if ("image".equals(type)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if ("video".equals(type)) {
            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if ("audio".equals(type)) {
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        final String selection = "_id=?";
        final String[] selectionArgs = new String[] {
                split[1]
        };

        return getDataColumn(context, contentUri, selection, selectionArgs);
    }
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {

    // Return the remote address
    if (isGooglePhotosUri(uri))
        return uri.getLastPathSegment();

    return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
    return uri.getPath();
}

return null;
}


public static String getDataColumn(Context context, Uri uri, String selection,
                               String[] selectionArgs) {

Cursor cursor = null;
final String column = "_data";
final String[] projection = {
        column
};

try {
    cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
            null);
    if (cursor != null && cursor.moveToFirst()) {
        final int index = cursor.getColumnIndexOrThrow(column);
        return cursor.getString(index);
    }
} finally {
    if (cursor != null)
        cursor.close();
}
return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
 }


public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}

 public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}

答案 1 :(得分:0)

我认为您的网址需要后缀。

这是MimeTypeMap的源代码:

/**
 * Returns the file extension or an empty string iff there is no
 * extension. This method is a convenience method for obtaining the
 * extension of a url and has undefined results for other Strings.
 * @param url
 * @return The file extension of the given url.
 */
public static String getFileExtensionFromUrl(String url) {
    if (!TextUtils.isEmpty(url)) {
        int fragment = url.lastIndexOf('#');
        if (fragment > 0) {
            url = url.substring(0, fragment);
        }

        int query = url.lastIndexOf('?');
        if (query > 0) {
            url = url.substring(0, query);
        }

        int filenamePos = url.lastIndexOf('/');
        String filename =
            0 <= filenamePos ? url.substring(filenamePos + 1) : url;

        // if the filename contains special characters, we don't
        // consider it valid for our matching purposes:
        if (!filename.isEmpty() &&
            Pattern.matches("[a-zA-Z_0-9\\.\\-\\(\\)\\%]+", filename)) {
            int dotPos = filename.lastIndexOf('.');
            if (0 <= dotPos) {
                return filename.substring(dotPos + 1);
            }
        }
    }

    return "";
}



    /**
 * Return the registered extension for the given MIME type. Note that some
 * MIME types map to multiple extensions. This call will return the most
 * common extension for the given MIME type.
 * @param mimeType A MIME type (i.e. text/plain)
 * @return The extension for the given MIME type or null iff there is none.
 */
public String getExtensionFromMimeType(String mimeType) {
    return MimeUtils.guessExtensionFromMimeType(mimeType);
}

和注意: MimeTypeMap在“package android.webkit”...