private List<String> FindFiles(Boolean fullPath) {
final List<String> tFileList = new ArrayList<String>();
String[] fileTypes = new String[]{"dat","doc","apk"....}; // file extensions you're looking for
FilenameFilter[] filter = new FilenameFilter[fileTypes .length];
int i = 0;
for (final String type : fileTypes) {
filter[i] = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("." + type);
}
};
i++;
}
FileUtils fileUtils = new FileUtils();
File[] allMatchingFiles = fileUtils.listFilesAsArray(
new File("/sdcard"), filter, -1);
for (File f : allMatchingFiles) {
if (fullPath) {
tFileList.add(f.getAbsolutePath());
}
else {
tFileList.add(f.getName());
}
}
return tFileList;
}
public class FileUtils {
public File[] listFilesAsArray(File directory, FilenameFilter[] filter,
int recurse) {
Collection<File> files = listFiles(directory, filter, recurse);
File[] arr = new File[files.size()];
return files.toArray(arr);
}
public Collection<File> listFiles(File directory,
FilenameFilter[] filter, int recurse) {
Vector<File> files = new Vector<File>();
File[] entries = directory.listFiles();
if (entries != null) {
for (File entry : entries) {
for (FilenameFilter filefilter : filter) {
if (filter == null
|| filefilter
.accept(directory, entry.getName())) {
files.add(entry);
Log.v("FileUtils", "Added: "
+ entry.getName());
}
}
if ((recurse <= -1) || (recurse > 0 && entry.isDirectory())) {
recurse--;
files.addAll(listFiles(entry, filter, recurse));
recurse++;
}
}
}
return files;
}
}
我該如何使用這段代碼?你能給我更多的細節嗎? – AndreaF
當然,請在您的活動中包含此代碼。然後使用列表 files = FindFiles(true)來獲取文件列表。使用「true」獲取完整路徑,使用「false」獲取文件名。 SDCARD上包含fileTypes中擴展名的所有文件都將被返回 –