英文:
TreeContentProvider just getting every Directory of my path. (File Filter)
问题
我试图获取路径中的每个文件夹。现在我只获取文件夹,但是一旦出现其他文件,就会出现JavaNullPointerException。我知道这是因为 listFiles(),但我不知道如何以其他方式让它工作。有人可以帮助我吗?
@Override
public Object[] getElements(Object inputElement) {
return File.listRoots();
}
@Override
public Object getParent(Object element) {
return ((File) element).getParentFile();
}
@Override
public boolean hasChildren(Object element) {
Object[] obj = getChildren(element);
return obj == null ? false : obj.length > 0;
}
@Override
public Object[] getChildren(Object parentElement) {
List<File> files = new ArrayList<>();
for (File file : ((File) parentElement).listFiles()) {
if (file.isDirectory()) {
files.add(file);
}
}
return files.toArray();
}
<details>
<summary>英文:</summary>
im trying to get every folder of my path.
Now Im getting just folders but as soon as some other file comes up it gives me a JavaNullPointerException.
I know its beacuse of ***listFiles()*** but I dont know how to let it work otherwise.
Can someone help me?
``
@Override
public Object[] getElements(Object inputElement) {
return File.listRoots();
}
@Override
public Object getParent(Object element) {
return ((File) element).getParentFile();
}
@Override
public boolean hasChildren(Object element) {
Object[] obj = getChildren(element);
return obj == null ? false : obj.length > 0;
}
@Override
public Object[] getChildren(Object parentElement) {
List<File> files = new ArrayList<>();
for (File file : ((File) parentElement).listFiles()) {
if (file.isDirectory()) {
files.add(file);
}
}
return ((File) parentElement).listFiles();
}
</details>
# 答案1
**得分**: 1
File.listFiles() 如果文件不是目录,则返回 null。这会导致您的异常。
要仅显示目录,请使用类似以下方式:
```java
@Override
public Object[] getChildren(Object parentElement) {
File parentFile = (File)parentElement;
if (!parentFile.isDirectory()) {
return new Object[0];
}
return parentFile.listFiles(File::isDirectory);
}
英文:
File.listFiles() returns null if the file is not a directory. This is causing your exception.
To just show directories use something like:
@Override
public Object[] getChildren(Object parentElement) {
File parentFile = (File)parentElement;
if (!parentFile.isDirectory()) {
return new Object[0];
}
return parentFile.listFiles(File::isDirectory);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论