简体   繁体   中英

how can i get the list of all files Inside a folder

please how can I list all files inside a folder? I try to do that with that code

    File theFolder = new File(Environment.getExternalStorageDirectory()+File.separator +"TestFolder");

    if(theFolder.exists())
    {
        Log.d("theFolder", "theFolderExiste ");
        File [] files = theFolder.listFiles();

        Log.d("Files", "files: "+files.length);
        
        for(File file : files)
        {
            Log.d("file ", "file name : "+file.getName());
        }
        

    }else
        {
            Log.d("theFolder", "we dont have that folder ");
        }

but hi give me that error Caused by: java.lang.NullPointerException: Attempt to get length of null array at com.joshuabutton.documentscanner.DisplayListOfFiles.onCreate(DisplayListOfFiles.java:76)

and I have files inside that folder as you can see in that pic在此处输入图像描述

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

There's two things you need to take in consideration.

1 - You need a read storage permission <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> to be able to read data that your app did not create

2 - Even with read storage permission, newer versions of android, do not allow to read folders this direct, check out this video , it might help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM