本文共 1892 字,大约阅读时间需要 6 分钟。
Uri的两种形式: 1. 以“content://”开头的 2. 以“file://”开头的 在Android 7.0中,应用间的数据交互,必须以content://开头。从合理利用内存的角度出发,在开发的过程中,用不到的file要进行回收。在需要使用系统应用时,数据的传输需要用Uri,本篇博客就是对根据Uri删除文件的知识总结。
context.getContentResolver().delete(uri, null, null);
File file = new File(FileUtils.getRealFilePath(context,uri));if (file.exists()&& file.isFile()){ file.delete();}
先把uri转换成path后,创建文件。判断是否存在,是不是文件而不是文件夹,最后调用delete()删除。有人说,这种删除方法,会把文件内容删掉,留一个空文件,我测试的时候还没有碰到。
uri转换成path的方法,借鉴其他人的文章,现在找不到文章了。/** * Try to return the absolute file path from the given Uri * * @param context * @param uri * @return the file path or null */ public static String getRealFilePath(final Context context, final Uri uri ) { if ( null == uri ) return null; final String scheme = uri.getScheme(); String data = null; if ( scheme == null ){ data = uri.getPath(); else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) { data = uri.getPath(); } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) { Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null ); if ( null != cursor ) { if ( cursor.moveToFirst() ) { int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA ); if ( index > -1 ) { data = cursor.getString( index ); } } cursor.close(); } } return data; }
综合成一个方法:
public void deleteUri(Context context, Uri uri) { if (uri.toString().startsWith("content://")) { // content://开头的Uri context.getContentResolver().delete(uri, null, null); } else { File file = new File(FileUtils.getRealFilePath(context,uri)); if (file.exists()&& file.isFile()){ file.delete(); } } }
转载地址:http://qctrl.baihongyu.com/