/**
* Return list of files from path. <FileName, FilePath>
*
* @param path - The path to directory with images
* @return Files name and path all files in a directory, that have ext = "jpeg", "jpg","png", "bmp", "gif"
*/
private List<String> getListOfFiles(String path) {
File files = new File(path);
FileFilter filter = new FileFilter() {
private final List<String> exts = Arrays.asList("jpeg", "jpg",
"png", "bmp", "gif");
@Override
public boolean accept(File pathname) {
String ext;
String path = pathname.getPath();
ext = path.substring(path.lastIndexOf(".") + 1);
return exts.contains(ext);
}
};
final File [] filesFound = files.listFiles(filter);
List<String> list = new ArrayList<String>();
if (filesFound != null && filesFound.length > 0) {
for (File file : filesFound) {
list.add(file.getName());
}
}
return list;
}
Điều này sẽ cung cấp cho bạn danh sách hình ảnh trong một thư mục. Bạn có thể sửa đổi mã để nhận tất cả các tệp.
Nguồn
2010-12-30 08:53:30
xin cảm ơn rất nhiều. – sajjoo
Bạn đã kiểm tra mã nguồn của hai phương thức 'list()' và 'listFiles()' chưa? Có một sự khác biệt nhỏ giữa chúng. Thú vị khi biết diff là gì. –
@Martjin: nội bộ, 'listFiles' sử dụng danh sách để tạo danh sách tên tệp và tạo đối tượng' Tệp'. Nhưng vì OP muốn chỉ có các tệp, tôi thích sử dụng 'listFiles' hơn. –