File exists and IS directory, but listFiles() returns null
For those with this problem, add this to AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Problem solved :D
EDIT: If this does not work just make sure if path is correct
Why can File.listFiles return null when called on a directory?
Add this to AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
This permission allow you to read files; if you don't use this permission then listFiles()
and list()
will both throw NullPointerException
.
And here is an example of showing all files in /storage/emulated/0/Download
:
String dir = "/storage/emulated/0/Download/";
File f = new File(dir);
String[] files = f.list();
for(int i=0; i<files.length; i++){
Log.d("tag", files[i]);
}
listFiles() returns null when it shouldn't. It used to work properly until recently and hasn't been modified
On Windows 7 (and later) the process will have to run with elevated privileges to write to C:/Windows
and similar directories. But if that was the problem it would result in a different error message.
What I suspect:
When running a 32-bit JVM under 64-bit Windows new File("C:/Windows/System32")
will point to C:\Windows\SysWOW64
and there is no info
-Folder under C:\Windows\SysWOW64\oobe
As a test:
public static void main(String[] args) {
File sysdir = new File("C:/Windows/System32/oobe/info");
for(File file:sysdir.listFiles()) {
System.out.println(file.getName());
}
}
runs fine with 64-bit-JRE and throws NullPointerException
under 32-bit-JRE on Windows 7 64-bit.
So perhaps you or another application recently installed a 32-bit-jre or changed your path to point to a 32-bit-jre and thus broke your application.
file.listFiles() returns null even though folder exists
In order to access the files, the permissions must be given in the manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Add this in your MainActivity.java (not in same class as it wont work for 1st time when app is installed cuz of not being async)
checkPermissionReadStorage(this);
Try this:
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
if (files != null)
{
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
}
Add this method to your class, i was getting the same crash as you said but after adding this i get the proper result -
D/Files: FileName:data
public static void checkPermissionReadStorage(Activity activity) {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1);
}
}
}
Let me know if you have any issue with this.
can only read folder/directory from main() ? listfiles() returns null?
Below code works fine, as long as path is correct. I assume your path must be invalid. As File::listFiles will return a null, if directory does not exist.
private List<String> get_files_paths(String data_path) {
File folder = new File(data_path);
if(!folder.exists() || !folder.isDirectory()){
throw new IllegalArgumentException("Invalid directory");
}
List<String> full_paths = new ArrayList<>();
for (File fileEntry : folder.listFiles()) {
if (fileEntry.isFile())
full_paths.add(fileEntry.getAbsolutePath());
}
return full_paths;
}
Related Topics
Why Is Double.Min_Value in Not Negative
How Does the Fetchmode Work in Spring Data JPA
How to Convert Camelcase into Human-Readable Names in Java
Is Iterating Concurrenthashmap Values Thread Safe
Sending Message to Specific User on Spring Websocket
Convert from Enum Ordinal to Enum Type
Builder Pattern in Effective Java
Calculate Distance in Meters When You Know Longitude and Latitude in Java
Does a Method's Signature in Java Include Its Return Type
Why Would One Declare an Immutable Class Final in Java
How to Make Spring Inject Value into a Static Field
Passing a String by Reference in Java
How to Use Mockito with Junit5
Change Name of Import in Java, or Import Two Classes with the Same Name
How to Pass an Arraylist to a Varargs Method Parameter
Why Should Wait() Always Be Called Inside a Loop