Android 使用ContentResolver和Regex从特定文件夹获取音乐

Android 使用ContentResolver和Regex从特定文件夹获取音乐,android,regex,android-contentresolver,Android,Regex,Android Contentresolver,我目前正试图从内容解析器检索特定文件夹中的音乐文件。我只想要该文件夹中的文件,而不是子文件夹中的文件。我通过以下操作获得了这些文件: String pattern = f.getAbsolutePath() + "/[^/]*"; // f is the folder where I want to search ArrayList<TrackInfo> retVal = new ArrayList<TrackInfo>(); Cursor mCursor = null;

我目前正试图从内容解析器检索特定文件夹中的音乐文件。我只想要该文件夹中的文件,而不是子文件夹中的文件。我通过以下操作获得了这些文件:

String pattern = f.getAbsolutePath() + "/[^/]*"; // f is the folder where I want to search
ArrayList<TrackInfo> retVal = new ArrayList<TrackInfo>();
Cursor mCursor = null;

String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0 AND " + DATA + " LIKE '" + f.getAbsolutePath() + "/%'";

Uri contentUri = Media.getContentUriForPath(Environment.getExternalStorageDirectory().getPath());
String projection[] = new String[]{DATA};

mCursor = context.getContentResolver().query(contentUri, projection, selection, null, DATA);

String data, fileName[];
while(mCursor.moveToNext()){

    data = mCursor.getString(0);        
    if(data.matches(pattern)){
        fileName = data.split("/");

        retVal.add(new TrackInfo(fileName[fileName.length-1], null, data, null, -1, R.drawable.notes, false));
    }           
}

mCursor.close();
结果是:

"/mnt/somepath/folder(with-parentheses)/test1*".matches("/mnt/somepath/folder(with-parentheses)/[^/]*") = false
"/mnt/somepath/folder/test2".matches("/mnt/somepath/folder/[^/]*") = true
我现在的问题是:
是否有更有效的方法获取文件夹中的所有音乐文件我已经尝试检查文件夹中的每个文件是否有模式(包含我找到的支持的媒体格式)。这种方法的问题在于,这些格式只是核心媒体格式——手机可能支持的不止这些。
为什么我的模式不起作用

非常感谢。

(以及许多其他字符,如
+
*
[
]
)都是正则表达式中的特殊字符。因此,有必要对其进行转义,即
\(
\)
,以指定文字字符

但是,在这种情况下,由于您是通过连接
f.getAbsolutePath()
来获得模式的,因此强烈建议您使用
f.getAbsolutePath()
中的所有字符。它将确保在正则表达式中没有任何字符被解释为特殊字符

String pattern = Pattern.quote(f.getAbsolutePath()) + "/[^/]*";

(当您在应用
模式.quote
后打印
模式时,您可能会注意到它将
\Q
\E
添加到原始字符串中。这是一种转义长字符串中所有字符的方法,Java正则表达式和其他几种正则表达式风格支持)。

您需要转义
()
,即
\(\)
,因为
()
是正则表达式中的特殊字符。谢谢,这很有效。如果你把它放在答案中,我会接受的。
String pattern = Pattern.quote(f.getAbsolutePath()) + "/[^/]*";