Roger Travis
Roger Travis

Reputation: 8548

How to list files in an android directory?

Here's my code so far:

String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";

        AssetManager mgr = getAssets();

        try {

            String list[] = mgr.list(path);
            Log.e("FILES", String.valueOf(list.length));

            if (list != null)
                for (int i=0; i<list.length; ++i)
                    {
                        Log.e("FILE:", path +"/"+ list[i]);
                    }

        } catch (IOException e) {
            Log.v("List error:", "can't list" + path);
        }

Yet while I do have files in that dir, it returns me list.length = 0... any ideas?

Upvotes: 151

Views: 300262

Answers (14)

Rohit S
Rohit S

Reputation: 794

Simple way to list files in android device in a specific folder

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

IN Kotlin

val fileRoot = Environment.getExternalStorageDirectory()
val yourDir = File(fileRoot, "FOLDER_NAME")
    for (f in yourDir.listFiles()!!) {
       if (f.isFile){
           print(f.name)
       }
    }

All the file name will be printed with the file extension

Upvotes: 0

Lasith
Lasith

Reputation: 58

For the people are still getting NullPointerException when they try to get file list, if you using Android API 29+ then you need to add

<application android:requestLegacyExternalStorage="true"...

in your AndroidManifest.xml file.

Then request for storage permission again.

Upvotes: 0

raghav-wd
raghav-wd

Reputation: 540

Yury's answer needs some elaboration for newer versions of Android.

First, make sure to defined READ_EXTERNAL_STORAGE permission in manifest file.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Include the below, for SDK greater than or equals to Android 10(Q).

<application android:requestLegacyExternalStorage="true"...</application>

Now you can list files in a directory.

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());
}

Upvotes: 2

Damercy
Damercy

Reputation: 1065

Updated working method

My minSdkversion is 21, so I'm using ContextCompat.checkSelfPermission() method to grant permissions apart from also adding the <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> in manifest. Thus, to get rid of the NullPointerException in spite of having files in your targeted directory, grant permissions as follows:-

MainActivity.java


public class MainActivity extends AppCompatActivity {
    /*Other variables & constants here*/  
    private final int READ_EXTERNAL_STORAGE=100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // ignore the button code

        Button btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openWebView();
            }
        });
    

         /*---------------------------- GRANT PERMISSIONS START-------------------------*/
        // Main part to grant permission. Handle other cases of permission denied
       //   yourself.
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},READ_EXTERNAL_STORAGE);

         /*---------------------------- GRANT PERMISSIONS OVER-------------------------*/
   }

And the function that list all the files (in MainActivity.java), thanks to @Yury:-
public void getDownloadedFile() {
        String path = Environment.getExternalStorageDirectory().toString()+"/Download/";
        Log.d("Files", "Path: " + path);
        File directory = new File(path);
        File[] files = directory.listFiles();
        if(directory.canRead() && files!=null) {
            Log.d("Files", "Size: " + files.length);
            for(File file: files)
                Log.d("FILE",file.getName());
        }
        else
            Log.d("Null?", "it is null");
    }

Upvotes: 4

Matt Emson
Matt Emson

Reputation: 1

If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn't work, it's worth reading this answer:

Android Q (10) ask permission to get access all storage. Scoped storage

I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won't continue to work in future versions.

Upvotes: 0

Yury
Yury

Reputation: 20936

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());
}

Upvotes: 401

Mujahid Khan
Mujahid Khan

Reputation: 1834

Try these

 String appDirectoryName = getResources().getString(R.string.app_name);
    File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getResources().getString(R.string.app_name));
    directory.mkdirs();
    File[] fList = directory.listFiles();
    int a = 1;
    for (int x = 0; x < fList.length; x++) {

        //txt.setText("You Have Capture " + String.valueOf(a) + " Photos");
        a++;
    }
    //get all the files from a directory
    for (File file : fList) {
        if (file.isFile()) {
            list.add(new ModelClass(file.getName(), file.getAbsolutePath()));
        }
    }

Upvotes: 0

gabriel
gabriel

Reputation: 131

In addition to all the answers above:

If you are on Android 6.0+ (API Level 23+) you have to explicitly ask for permission to access external storage. Simply having

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

in your manifest won't be enough. You also have actively request the permission in your activity:

//check for permission
if(ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
    //ask for permission
    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_PERMISSION_CODE);
}

I recommend reading this: http://developer.android.com/training/permissions/requesting.html#perm-request

Upvotes: 13

Roc Boronat
Roc Boronat

Reputation: 12171

There are two things that could be happening:

  • You are not adding READ_EXTERNAL_STORAGE permission to your AndroidManifest.xml
  • You are targeting Android 23 and you're not asking for that permission to the user. Go down to Android 22 or ask the user for that permission.

Upvotes: 1

Iman Marashi
Iman Marashi

Reputation: 5753

Try this:

public class GetAllFilesInDirectory {

public static void main(String[] args) throws IOException {

    File dir = new File("dir");

    System.out.println("Getting all files in " + dir.getCanonicalPath() + " including those in subdirectories");
    List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
    for (File file : files) {
        System.out.println("file: " + file.getCanonicalPath());
    }

}

}

Upvotes: 1

rdkit
rdkit

Reputation: 256

String[] listOfFiles = getActivity().getFilesDir().list();

or

String[] listOfFiles = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS).list();

Upvotes: 1

Dan Brough
Dan Brough

Reputation: 3025

I just discovered that:

new File("/sdcard/").listFiles() returns null if you do not have:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

set in your AndroidManifest.xml file.

Upvotes: 50

Reed
Reed

Reputation: 14984

Well, the AssetManager lists files within the assets folder that is inside of your APK file. So what you're trying to list in your example above is [apk]/assets/sdcard/Pictures.

If you put some pictures within the assets folder inside of your application, and they were in the Pictures directory, you would do mgr.list("/Pictures/").

On the other hand, if you have files on the sdcard that are outside of your APK file, in the Pictures folder, then you would use File as so:

File file = new File(Environment.getExternalStorageDirectory(), "Pictures");
File[] pictures = file.listFiles();
...
for (...)
{
log.e("FILE:", pictures[i].getAbsolutePath());
}

And relevant links from the docs:
File
Asset Manager

Upvotes: 17

Alexander
Alexander

Reputation: 48272

Your path is not within the assets folder. Either you enumerate files within the assets folder by means of AssetManager.list() or you enumerate files on your SD card by means of File.list()

Upvotes: 2

Related Questions