How to list files in an android directory?
In order to access the files, the permissions must be given in the manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Try this:
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
Android: How to list all the files in a directory in to an array?
I think the problem you are facing is related to the external storage directory file path. Don't use whole path as variable if you can access with environment.
String path = Environment.getExternalStorageDirectory().toString()+"/images/scenes";
Also, you can use the API listfiles() with file object and it will work. For eg ::
File f = new File(path);
File file[] = f.listFiles();
List all the files from all the folder in a single list
Try this:
.....
List<File> files = getListFiles(new File("YOUR ROOT"));
....
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")){
inFiles.add(file);
}
}
}
return inFiles;
}
or variant without recursion:
private List<File> getListFiles2(File parentDir) {
List<File> inFiles = new ArrayList<>();
Queue<File> files = new LinkedList<>();
files.addAll(Arrays.asList(parentDir.listFiles()));
while (!files.isEmpty()) {
File file = files.remove();
if (file.isDirectory()) {
files.addAll(Arrays.asList(file.listFiles()));
} else if (file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
return inFiles;
}
Related Topics
How to Set a Font for the Options Menu
Android Keeps Caching My Intents Extras, How to Declare a Pending Intent That Keeps Fresh Extras
Coupling Firebaserecyclerviewadapter to a Boolean/String Map.Entry
Date Formatting Based on User Locale on Android
Checking Internet Connection on Android
Firebase Chat App Setvalue Failed Error With a Public Database
Using Jaxb with Google Android
Error Inflating Class Android.Support.V7.Widget.Toolbar
Get the Background Color of a Button in Android
Realmchangelistener Does Not Get Called When Realm Gets Updated in Notificationlistenerservice
Register Application Class in Manifest
How to Add "Go Back" Function in Webview Inside Fragment
Programmatic Views How to Set Unique Id'S
Android - Controlling a Task with Timer and Timertask
How to Detect When a User Plugs Headset on Android Device? (Opposite of Action_Audio_Becoming_Noisy)