how to get the file names stored in sd card in android
any help will be appreciative. thanks a lot.
Environment.getExternalStorageDirectory
will give you a File
corresponding to the SDCARD. Then you'll just have to use File
methods.
That should be something like that :
File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(sdCardRoot, "yourpath");
for (File f : yourDir.listFiles()) {
if (f.isFile())
String name = f.getName();
// make something with the name
}
A little note of advice : from KitKat and above, this requires the READ_EXTERNAL_STORAGE
permission.
/**
* 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;
}
This will give you the list of images in a folder. You can modify the code to get all files.
In Android 5.0 Lollipop, I found that we need add the permission to Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If not, we could not see any file in sdcard. I take an hour to find this!
ArrayList<String>nameList = new ArrayList<String>();
File yourDir = new File(Environment.getExternalStorageDirectory(), "/myFolder");
for (File f : yourDir.listFiles())
{
if (f.isFile())
{
nameList.add(f.getName);
}
}
If you want to retrieve all files and folder from a specific path of FOLDER then use this code it will help you
String path="/mnt/sdcard/dcim"; //lets its your path to a FOLDER
String root_sd = Environment.getExternalStorageDirectory().toString();
File file = new File(path) ;
File list[] = file.listFiles();
for(File f:list)
{
filename.add(f.getName());//add new files name in the list
}
精彩评论