My question is: if this two functions have something different? I mean I know that they return something different, but is it possible that number of elements in one would be different then in the second one. I will try to explain. I implemented TreeModel for one of my class trying to make nice view on files on the PC basing on JTree. So here is the part of it:
public Object getChild(Object parent, int index) {
File[] children = ((File) parent).listFiles();
if(children == null || index < 0 || index >= children.length) {
return null;
}
File result = new MyFile(children[index]);
return result;
}
public int getChildCount(Object parent) {
//---
//String[] children = ((File)parent).list();
File[] children = ((File)parent).listFiles();
//---
if(children == null) {
return 0;
}
return children.length;
}
I marked interesting code. If I changed this two lines for this commented one, sometimes I get NullPointerException
after loading TreeModel: jtree.setModel(treeModel);
. This uncommented does not cause any trouble. I checked the docs and it says nothing unusual including returning null by both methods. What is going on here?
listFiles() returns the array of abstract pathnames defining the files in the directory denoted by this abstract pathname.
Eclipse looks for the file exactly in the root folder of the project (project name folder). So you can have src/test.in to locate file inside src folder of the project.
Both methods do essentially the same, look at http://www.docjar.com/html/api/java/io/File.java.html for details.
As already pointed, but clarified only within the comments in post from D.R
list
method returns String array
with filenames (files and
directories)
listFiles
return array of class File
of the same
See doc pages, eg. https://docs.oracle.com/javase/7/docs/api/java/io/File.html
String[] list()
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
I am not sure why both methods exist, probably String array will be faster and less memory consuming than File array one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With