列出 android 中从外部存储到 ListView 小部件的所有特定类型的文档文件。
ArrayList<String> filenames;
ArrayAdapter<String> adapter;
// onCreate method
filelist = findViewById(R.id.fileList); //filelist is ListView widget
filenames = new ArrayList<>();
getFiles(); // files funtions
adapter=new ArrayAdapter<>(YourActivity.this, android.R.layout.simple_list_item_1, filenames);
filelist.setAdapter(adapter);
// getFiles() is method for getting and filtering all doccuments files from external storage
private void getFiles() {
File path = Environment.getExternalStorageDirectory();
String filename ;
Queue<File> files = new LinkedList<>(); //Linklist
files.addAll(Arrays.asList(path.listFiles())); //adding all files of path in linklist
while (!files.isEmpty()){
File file = files.remove();
if (file.isDirectory()){
files.addAll(Arrays.asList(file.listFiles()));
}
else if (file.getName().endsWith(".doc")||file.getName().endsWith(".xls")||file.getName().endsWith(".ppt")){ //filtering files
filename = file.getName(); // according to their extension
filenames.add(filename); //filenames is string ListArray
}
}
}
只需将字符串值更改为.doc
或.xls
.your_file_extension