How to list files in an android directory?

Android

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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.

Solution 3 - Android

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:
http://developer.android.com/reference/java/io/File.html">File</a>
http://developer.android.com/reference/android/content/res/AssetManager.html">Asset Manager

Solution 4 - Android

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

Solution 5 - Android

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

Solution 6 - Android

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

Solution 7 - Android

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

or

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

Solution 8 - Android

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

}

}

Solution 9 - Android

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.

Solution 10 - Android

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

Solution 11 - Android

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

Solution 12 - Android

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.

Solution 13 - Android

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.

Solution 14 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoger TravisView Question on Stackoverflow
Solution 1 - AndroidYuryView Answer on Stackoverflow
Solution 2 - AndroidDan BroughView Answer on Stackoverflow
Solution 3 - AndroidReedView Answer on Stackoverflow
Solution 4 - AndroidgabrielView Answer on Stackoverflow
Solution 5 - AndroidDamercyView Answer on Stackoverflow
Solution 6 - AndroidAlexander KulyakhtinView Answer on Stackoverflow
Solution 7 - AndroidrdkitView Answer on Stackoverflow
Solution 8 - AndroidIman MarashiView Answer on Stackoverflow
Solution 9 - AndroidRoc BoronatView Answer on Stackoverflow
Solution 10 - Androidraghav-wdView Answer on Stackoverflow
Solution 11 - AndroidMujahid KhanView Answer on Stackoverflow
Solution 12 - AndroidMatt EmsonView Answer on Stackoverflow
Solution 13 - Androidz1nc0r3View Answer on Stackoverflow
Solution 14 - AndroidRohit SView Answer on Stackoverflow