The File
from which I'm trying to create the array Files[] currentDir
via File.listFiles()
consists of one subdirectory which happens to be a Link (see image link below).
In the Activity where I'm trying to create currentDir
, I'm trying to et the length of it afterwards, but I get the NullpointerException: Attempt to get length of null array
.
the corresponding code:
File directory = new File("/storage/self")
currentDir = directory.listFiles();
...
for(File mFile:currentDir){...}
Here's the link to my image: AVD File Explorer.
Using a debugger, I foud out, that currentDir
stayed empty (null), indeed.
My guess is, that it's because the directory primary
is actually a link.
I found the following thread, and I tried to implement the suggestions: Similar Question on SOF.
I tried:
File directory = directory.getCanonicalFile();
String[] files = directory.listFiles();
and I tried:
...
String mPath = null;
try {
mPath = directory.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
File[] currentDir = null;
Path dirPath = Paths.get(mPath);
if (Files.isSymbolicLink(dirPath)) {
Path[] files = null;
try {
dirPath = Files.readSymbolicLink(dirPath);
files = Files.list(dirPath).toArray(size -> new Path[size]);
currentDir = new File[files.length];
for(int i = 0; i <files.length; i++){
currentDir[i] = files[i].toFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
else{
currentDir = directory.listFiles();
}
...
for(File mFile:currentDir){...}
(Honestly, I don't like that approach, that's why my question doesn't focus on how to recognise a Link.)
The activity never enters the if statement if (Files.isSymbolicLink(dirPath)) {...}
, probably because the directory
itself isn't a Link so it's useless, but then again, how am I supposed to get that subdirectory in the first place, if listFiles()
doesn't work?
Is there an approach to solve that problem?