[英]Using ContentResolver and Regex to get music from specific folder
我目前正在嘗試從ContentResolver檢索特定文件夾中的音樂文件。 我只希望該文件夾中的文件,而不是子文件夾中的文件。 我通過執行以下操作獲得了這些文件:
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();
這在大多數情況下都是可行的。 但是現在我的模式似乎有問題。 問題在於,如果模式包含括號,則data.matches(pattern)
始終返回false。 我嘗試過的示例是:
String pattern1 = "/mnt/somepath/folder(with-parentheses)/[^/]*";
String pattern2 = "/mnt/somepath/folder/[^/]*";
String string1 = "/mnt/somepath/folder(with-parentheses)/test1";
String string2 = "/mnt/somepath/folder/test2";
System.out.println("\"" + string1 + "\"" + ".matches(\"" + pattern1 + "\") = " + string1.matches(pattern1));
System.out.println("\"" + string2 + "\".matches(\"" + pattern2 + "\") = " + string2.matches(pattern2));
輸出為:
"/mnt/somepath/folder(with-parentheses)/test1*".matches("/mnt/somepath/folder(with-parentheses)/[^/]*") = false
"/mnt/somepath/folder/test2".matches("/mnt/somepath/folder/[^/]*") = true
我的問題是:
有沒有更有效的方法來獲取文件夾中的所有音樂文件? -我已經嘗試檢查文件夾中的每個文件是否存在模式(包含在這里找到的支持的媒體格式)。 這種方法的問題在於這些格式只是核心媒體格式 -手機可能支持的格式更多。
為什么我的模式不起作用?
非常感謝。
(
, )
(和許多其他如+
, *
, [
, ]
, .
)是在正則表達式的特殊字符。 因此,有必要對它們進行轉義,即\\(
, \\)
以指定文字字符。
但是,在這種情況下,由於您是通過串聯f.getAbsolutePath()
獲得模式的,因此強烈建議您使用Pattern.quote(String)
在f.getAbsolutePath()
文字中制作所有字符。 它將確保在正則表達式中沒有任何字符被解釋為特殊字符。
String pattern = Pattern.quote(f.getAbsolutePath()) + "/[^/]*";
(在應用Pattern.quote
之后打印出pattern
,您可能會注意到它在原始字符串中添加了\\Q
和\\E
這是一種對長字符串中的所有字符進行轉義的方法,Java regex和其他幾個regex支持口味)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.