[android] 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?

This question is related to android

The answer is


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


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.


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

or

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

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


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.

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


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

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

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.


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

}

}