Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在android中通过Uri获取文件扩展名_Android - Fatal编程技术网

在android中通过Uri获取文件扩展名

在android中通过Uri获取文件扩展名,android,Android,我想从电话中检查所选文件的扩展名。 当我选择时,我得到:content://com.android.providers.media.documents/document/image%3A20247 获取扩展名的方法返回空值: public static String getMimeType(String url) { String type = null; String extension = MimeTypeMap.getFileExtensionFromUr

我想从电话中检查所选文件的扩展名。 当我选择时,我得到:
content://com.android.providers.media.documents/document/image%3A20247
获取扩展名的方法返回空值:

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

知道为什么吗?

试着用这个,它对我有用

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());
}

我认为你的url需要后缀

这是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);
}
/**
*如果没有扩展名,则返回文件扩展名或空字符串
*分机。该方法是一种方便的获取数据的方法
*url的扩展名,并具有其他字符串的未定义结果。
*@param-url
*@返回给定url的文件扩展名。
*/
公共静态字符串getFileExtensionFromUrl(字符串url){
如果(!TextUtils.isEmpty(url)){
int fragment=url.lastIndexOf('#');
如果(片段>0){
url=url.substring(0,片段);
}
int query=url.lastIndexOf(“?”);
如果(查询>0){
url=url.substring(0,查询);
}
int filenamePos=url.lastIndexOf('/');
字符串文件名=
0