Android: How to search files on sd card?

落爺英雄遲暮 提交于 2019-12-09 03:48:39

问题


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:


  1. 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)
  2. you will loop through all of those directory beneath it, preferably, recursive.
  3. store each file name that match your search criteria
  4. upon finishing, do whatever you want to do with the result.


来源:https://stackoverflow.com/questions/13990826/android-how-to-search-files-on-sd-card

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!