0

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(); } 
4
  • Null pointer where exactly? Commented Sep 10, 2020 at 15:23
  • Here : for (File file : ((File) parentElement .listFiles()) Commented Sep 10, 2020 at 15:50
  • Well listFiles returns null if the File is not a directory causing that error. You must check if it is directory before doing that. Commented Sep 10, 2020 at 16:19
  • Yeah I thought of that, do you have an example code for it? Commented Sep 10, 2020 at 16:21

1 Answer 1

1

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); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.