148

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?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
Roger Travis
  • 8,402
  • 18
  • 67
  • 94

14 Answers14

391

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());
}
Noman
  • 887
  • 1
  • 15
  • 34
Yury
  • 20,618
  • 7
  • 58
  • 86
  • 7
    Thanks Yury, strangely file.length gives a NullPointerException... any ideas? Spasibo! – Roger Travis Dec 27 '11 at 17:36
  • 9
    I think that you do not have files in the specified folder. Try to check file[] for null. If it is null then you do not have any results and file.length causes the exception. – Yury Dec 27 '11 at 17:41
  • 4
    Appears it was just missing a "/" :) Thanks! – Roger Travis Dec 27 '11 at 17:45
  • 2
    Worked like Charm! My mobile is Moto G4, **Android N**. If anyone are facing `can't play video error`. You need to go to your mobile `settings --> apps --> your app --> permissions --> enable storage.` Should do this manually if you are facing this error. Make sure that you have `` in your manifest. For the people who are facing `NullPointerException` - you are trying to access the files in the app's internal storage which are private sorry you can't do that. – coderpc Jun 23 '17 at 16:00
  • is there something like fileList().clear();? , so i can reuse this method – user55924 Mar 12 '18 at 02:48
  • if file.length gives NullPointerException even after adding permission in manifest file, go to your app settings and allow storage permission manually – Sumit Jun 11 '21 at 13:20
49

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.

Dan Brough
  • 2,745
  • 1
  • 24
  • 24
17

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

Reed
  • 14,703
  • 8
  • 66
  • 110
13

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

gabriel
  • 131
  • 1
  • 4
3

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");
    }
Damercy
  • 939
  • 8
  • 10
2

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());
}
raghav-wd
  • 410
  • 4
  • 12
  • You should probably reference @Yury's original, accepted answer, as you have copied 90% of it and simply added the update for Android 10. – c.fogelklou Jul 15 '21 at 12:51
  • I'm new to stack overflow as a contributor, I had this problem and thought his answer was not complete so posted this. I'll wait for more views on it if people don't find it helpful I'll remove it, thanx mate for your view appreciate it! – raghav-wd Jul 15 '21 at 20:35
  • I think your answer would be OK if you stated that Yuri's answer needs some elaboration for newer versions of Android. – c.fogelklou Jul 16 '21 at 06:08
2

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

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
1
String[] listOfFiles = getActivity().getFilesDir().list();

or

String[] listOfFiles = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS).list();
rdkit
  • 246
  • 3
  • 16
1

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

}

}
Elemental
  • 7,365
  • 2
  • 28
  • 33
Iman Marashi
  • 5,593
  • 38
  • 51
1

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.
Roc Boronat
  • 11,395
  • 5
  • 47
  • 59
0

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()));
        }
    }
Mujahid Khan
  • 1,712
  • 1
  • 18
  • 24
0

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.

0

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.

Abhishek Dutt
  • 1,308
  • 7
  • 14
  • 24
Lasith M
  • 48
  • 7
0

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

Rohit S
  • 714
  • 5
  • 7