gumba
gumba

Reputation: 72

How to read files and folders in a specific directory on android

I am trying to read all files and folders in a directory specified by the user.

I use:

File file = new File("/");
String[] files = file.list();

This works and gives me a list of the file names and folders in the root directory.
This works fine, but when I specify anything other then "/" it crashes.

How do I fix this, am I not giving it a valid path or is there something wrong with my code?

Upvotes: 3

Views: 2995

Answers (1)

Rohan Kandwal
Rohan Kandwal

Reputation: 9336

/ is the root of android and there exists not folder name storage, so when you are using

String[] files = file.list();

you are asking android to give the list of files inside storage which doesn't even exists. Thus, you are getting errors.

Best practice is to assume that the folder might not exist, even if you are sure it will eg user can delete a folder that you created on the SDCard which will cause crashes in your apps. So use the following code

if(file.exists()){
String [] filenames = file.list();
}

And this is just my guess but i think you are searching for SDCard, if so then use

Environment.getExternalStorageDirectory()

with permission to read SDCard files.

Update :- For reading files in internal and external memory please see the following link https://stackoverflow.com/a/17546843/1979347

Upvotes: 1

Related Questions