Android, how can I get a list of all files in a folder?
Asked Answered
P

7

31

I need the name (String) of all files in res/raw/ directory.

I tried:

File f = new File("/"); 
String[] someFiles = f.list();

It looks like the root directory is the root of the android emulator...and not my computers root directory. That makes enough sense, but doesn't really help me find out where the raw folder exists.

Update: Thanks for all the great replies. It appears that some of these are working, but only getting me half way. Perhaps a more detailed description will aid

I want to get all the mp3 files in the raw folder so I can get all the names, then add them to a URI to play a random MP3 in the following way...

String uriStr = "android.resource://"+ "com.example.phone"+ "/" + "raw/dennis";
Uri uri = Uri.parse(uriStr);
singletonMediaPlayer = MediaPlayer.create(c, uri);

When I put "dennis.mp3" into the assets folder, it does show up as expected, however, using the above code, I can't access that MP3 anymore, unless there is something along the line of:

String uriStr = "android.assets://"+ "com.example.phone"+ "/" + "dennis";
Uri uri = Uri.parse(uriStr);
Philharmonic answered 30/6, 2011 at 18:57 Comment(1)
I suspect that you can't reference a raw asset by URI. You may need to pass it as an AssetFileDescriptor object. Just call getResources().openRawResourceFd(resourceID);Requisite
R
69

To list all the names of your raw assets, which are basically the filenames with the extensions stripped off, you can do this:

public void listRaw(){
    Field[] fields=R.raw.class.getFields();
    for(int count=0; count < fields.length; count++){
        Log.i("Raw Asset: ", fields[count].getName());
    }
}

Since the actual files aren't just sitting on the filesystem once they're on the phone, the name is irrelevant, and you'll need to refer to them by the integer assigned to that resource name. In the above example, you could get this integer thus:

int resourceID=fields[count].getInt(fields[count]);

This is the same int which you'd get by referring to R.raw.whateveryounamedtheresource

Requisite answered 30/6, 2011 at 19:46 Comment(7)
To clarify use java.lang.reflect.Field[]Rosalynrosalynd
@Captain Blammo, what about a directory on a host? Can I get list of files in directory on the Internet host?Zealot
No, that's a completely different technique. This is only for local files inside your resource directory at compile time.Requisite
This does not work if we want to iterate over the R class of a derived project. Any idea on how to deal with such aspect ?Brendis
@MikaëlMayer: pass in the R class of the derived project as parameter. Because of the way android resource merging works, only the R of the derived project will contain the generated fields.Ban
you mean com.package.myderivedproject.R.raw.class ? But I don't have access to the com.package.myderivedproject in the base library project.Brendis
why it does not work if I use buildFlavors. How to fix it? Any ideas?Fist
U
10

This code will retrieve all the files from 'New Foder' of sdCard.

    File sdCardRoot = Environment.getExternalStorageDirectory();
    File yourDir = new File(sdCardRoot, "New Folder");
    for (File f : yourDir.listFiles()) {
        if (f.isFile())         
        {               
           String name = f.getName();           
           Log.i("file names", name);          

        }

     }

and also make sure to add android sd card write permission in your manifest.xml file

Ursuline answered 2/1, 2014 at 8:55 Comment(0)
R
4

I need the name (String) of all files in res/raw/

There are no files in res/raw/ on the device. Those are resources. There is no good way to iterate over resources, other than by using reflection to iterate over the static data members of the R.raw class to get the various ID names and values.

but doesn't really help me find out where the raw folder exists.

As a folder, it only exists on your development machine. It is not a folder on the device.

Ruyter answered 30/6, 2011 at 19:1 Comment(0)
H
3

You can use AssetManager:

As far as I can remember, you will have list with (just try different paths):

final String[] allFilesInPackage = getContext().getResources().getAssets().list("");
Heterochromatic answered 30/6, 2011 at 19:6 Comment(0)
A
2

Look at http://developer.android.com/reference/android/content/res/Resources.html You can generally acquire the Resources instance associated with your application with getResources().

Resources class provides access to http://developer.android.com/reference/android/content/res/AssetManager.html (see to getAssets() method). And finally obtain access to your packaged (apk) files with AssetManager.list() method. Enjoy!

Areaway answered 30/6, 2011 at 19:8 Comment(0)
P
1

From a Context, you can call something like this:

getResources().getAssets().list("thePath");

link to documentation

Pfaff answered 30/6, 2011 at 19:3 Comment(3)
That works for assets, and may be a better choice for the OP in this case. But assets are not the same as raw resources.Ruyter
@Commons: I suppose I was under the impression that everything under /res was considered an asset...hmm...Pfaff
Assets refers to assets/, not res/raw/, last I checked.Ruyter
R
0

Here are two solutions for Kotlin.

Method 1

// Make sure to add this dependency in your build file
// implementation(kotlin("reflect"))

for (property in R.raw::class.staticProperties) {
    val itsName = property.name
    val itsValue = property.get() // Aka, the resource ID
}

Note that, to get properties that are not static (instance members), instead of staticProperties above, use memberProperties and pass your object instance to the get() function call.

Method 2

val fields = R.raw::class.java.getFields()
for (field in fields) {
    val itsName = field.name
    val itsValue = field.getInt(field) // Aka, the resource ID
}
Rowdy answered 23/9, 2023 at 8:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.