Android 按关键字或文件后缀搜索文件

本文介绍了在Android平台上如何根据关键字和文件后缀进行文件搜索。内容包括了MIME类型的重要性以及如何处理系统数据库刷新问题的代码示例。如有疑问,作者承诺会及时回复评论。
摘要由CSDN通过智能技术生成

查找的情况分为两种:关键字、文件类型。


按关键字查找:

 private List
   
   
    
     searchKeyWord(Context context, String keyword) {
        List
    
    
     
      fileList = new ArrayList<>();
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Files.getContentUri("external");
        Cursor cursor = resolver.query(uri,
                new String[]{MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE},
                MediaStore.Files.FileColumns.TITLE + " LIKE '%" + keyword + "%'",
                null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                FileBean bean = new FileBean();
                String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA));
                bean.setName(path.substring(path.lastIndexOf("/") + 1));
                bean.setSize(cursor.getLong(cursor.getColumnIndexOrThrow(
                        MediaStore.Files.FileColumns.SIZE)));
                fileList.add(bean);
            }
        }
        cursor.close();
        return fileList;
    }
    
    
   
   
代码主要通过 ContentResolver 对系统数据库进行查询。
/**
     * Query the given URI, returning a {@link Cursor} over the result set.
     * <p>
     * For best performance, the caller should follow these guidelines:
     * <ul>
     * <li>Provide an explicit projection, to prevent
     * reading data from storage that aren't going to be used.</li>
     * <li>Use question mark parameter markers such as 'phone=?' instead of
     * explicit values in the {@code selection} parameter, so that queries
     * that differ only by those values will be recognized as the same
     * for caching purposes.</li>
     * </ul>
     * </p>
     *
     * @param uri The URI, using the content:// scheme, for the content to
     *         retrieve.
     * @param projection A list of which columns to return. Passing null will
     *         return all columns, which is inefficient.
     * @param selection A filter declaring which rows to return, formatted as an
     *         SQL WHERE clause (excluding the WHERE itself). Passing null will
     *         return all rows for the given URI.
     * @param selectionArgs You may include ?s in selection, which will be
     *         replaced by the values from selectionArgs, in the order that they
     *         appear in the selection. The values will be bound as Strings.
     * @param sortOrder How to order the rows, formatted as an SQL ORDER BY
     *         clause (excluding the ORDER BY itself). Passing null will use the
     *         default sort order, which may be unordered.
     * @return A Cursor object, which is positioned before the first entry, or null
     * @see Cursor
     */
    public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri,
            @Nullable String[] projection, @Nullable String selection,
            @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        return query(uri, projection, selection, selectionArgs, sortOrder, null);
    }
projection:你希望查询到的内容。
selection:查询条件。
selectionArgs:查询条件里面如果有?,就把?的值放进这个数组里面。
sortOrder:排序。

这里通过关键字进行查找。查询语句请参照上方或自行百度修改。
获取文件名这里并没有直接使用 MediaStore.Files.FileColumns.TITLE,而是使用 MediaStore.Files.FileColumns.DATA 获取到文件路径再获取到文件名。
因为使用 MediaStore.Files.FileColumns.TITLE 获取的到文件名没有文件格式。

按文件类型查找:
 private List
    
    
     
      searchType(Context context, String type) {
        List
     
     
      
       fileList = new ArrayList<>();
        String t = "";
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Files.getContentUri("external");
        for (int i = 0; i < MIMETable.length; i++) {
            if (type.equals(MIMETable[i][0])) {
                t = MIMETable[i][1];
            }
        }
        Cursor cursor = resolver.query(uri,
                new String[]{MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE,},
                MediaStore.Files.FileColumns.MIME_TYPE + " = '" + t + "'",
                null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                FileBean bean = new FileBean();
                String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA));
                bean.setName(path.substring(path.lastIndexOf("/") + 1));
                bean.setSize(cursor.getLong(cursor.getColumnIndexOrThrow(
                        MediaStore.Files.FileColumns.SIZE)));
                fileList.add(bean);
            }
        }
        cursor.close();
        return fileList;
    }
     
     
    
    

通过文件的后缀获取MIME,然后到数据库查找。

MIME类型可能有点不对,需要的自己百度一份最新的。

MIME列表:

  /**
     * -- MIME 列表 --
     */
    private static final String[][] MIMETable =
            {
                    // --{后缀名, MIME类型}   --
                    {"3gp", "video/3gpp"},
                    {"3gpp", "video/3gpp"},
                    {"aac", "audio/x-mpeg"},
                    {"amr", "audio/x-mpeg"},
                    {"apk", "application/vndandroidpackage-archive"},
                    {"avi", "video/x-msvideo"},
                    {"aab", "application/x-authoware-bin"},
                    {"aam", "application/x-authoware-map"},
                    {"aas", "application/x-authoware-seg"},
                    {"ai", "application/postscript"},
                    {"aif", "audio/x-aiff"},
                    {"aifc", "audio/x-aiff"},
                    {"aiff", "audio/x-aiff"},
                    {"als", "audio/x-alpha5"},
       
  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值