Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.list() vs File.listFiles()

Tags:

java

swing

jtree

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?

like image 919
Fuv Avatar asked Mar 12 '13 18:03

Fuv


People also ask

What does the file listFiles () method return?

listFiles() returns the array of abstract pathnames defining the files in the directory denoted by this abstract pathname.

Where does Java look for files?

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.


2 Answers

Both methods do essentially the same, look at http://www.docjar.com/html/api/java/io/File.java.html for details.

like image 147
D.R. Avatar answered Sep 22 '22 14:09

D.R.


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

like image 31
xxxvodnikxxx Avatar answered Sep 19 '22 14:09

xxxvodnikxxx