问题
How can I search files on my sd-card given an entered string?
I'd like to search for "test" and want to get a list with all files that contain in the name the string "test":
testfile.txt
filetest.jpg
thisisatestfile.xml
etc.
回答1:
You can use ListFiles() of Apache Commons IO, passing a RegexFileFilter FileFilter.
Example using Commons IO jar library in your Android project :
Collection<File> files = FileUtils.listFiles(
Environment.getExternalStorageDirectory(),
new RegexFileFilter(".*test.*"),
TrueFileFilter.TRUE);
for(File f : files){
//---do something---
}
Also, run this code in a separate thread, consider using AsyncTask
.
回答2:
- you will need to get the top-most directory you want to search. Because, if you start search from / (root), it will waste too much resources. Best start from /sdcard (or whatever it is that top user data directory)
- you will loop through all of those directory beneath it, preferably, recursive.
- store each file name that match your search criteria
- upon finishing, do whatever you want to do with the result.
来源:https://stackoverflow.com/questions/13990826/android-how-to-search-files-on-sd-card