android like 全局模糊查找文件命名 通过条件通过 like %search%
如果查找的关键字是% 那么就成了 like %%% 就会查找出所有的文件
解决办法是先把正则里面的匹配符 替换成转义字符
private static String sqliteEscape(String keyWord) { keyWord = keyWord.replace("/", "//"); keyWord = keyWord.replace("'", "''"); keyWord = keyWord.replace("[", "/["); keyWord = keyWord.replace("]", "/]"); keyWord = keyWord.replace("%", "/%"); keyWord = keyWord.replace("&", "/&"); keyWord = keyWord.replace("_", "/_"); keyWord = keyWord.replace("(", "/("); keyWord = keyWord.replace(")", "/)"); return keyWord; }
这个时候 还需要 告诉sql语句那个字符是转义的 需用到 escape "/"替换转义字符
public static void fileSearch(Context context, String inputString) { String searchTxt = sqliteEscape(inputString); ContentResolver contentResolver = context.getContentResolver(); String[] projection = {MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.DATE_MODIFIED, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.TITLE, MediaStore.Files.FileColumns.MIME_TYPE}; String selection = MediaStore.Files.FileColumns.TITLE + " LIKE ? escape '/' "; String searchStr = "%"+searchTxt+"%"; String[] selectionArgs = new String[]{searchStr}; Cursor cursor = null; try { cursor = contentResolver.query(MediaStore.Files.getContentUri("external"), projection, selection, selectionArgs, MediaStore.Files.FileColumns.DATE_MODIFIED + " desc"); if (cursor != null) { int fileId; String filePath; File file; long size; long modifiedTime; while (cursor.moveToNext()) { //.... } } } catch (Exception e) { if (DEBUG) { Log.e(TAG, "", e); } } finally { try { if (cursor != null) { cursor.close(); } } catch (Exception e) { if (DEBUG) { Log.e(TAG, "", e); } } } }