Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

Android, how do can I get a list of all files in a folder?

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

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...