File.list()vs File.listFiles()

Fuv*_*Fuv 12 java swing jtree

我的问题是:如果这两个功能有什么不同?我的意思是我知道他们会返回不同的东西,但是在一个元素中的元素数量可能与第二个元素中的元素数量不同.我会尽力解释.我为我的一个类实现了TreeModel,试图在基于JTree的PC上查看文件.所以这是它的一部分:

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;
}
Run Code Online (Sandbox Code Playgroud)

我标记了有趣的代码.如果我改变了这两条线为这个评论一个,有时我得到NullPointerException装载的TreeModel后:jtree.setModel(treeModel);.这没有注释不会造成任何麻烦.我检查了文档,它说没有什么不寻常的,包括通过两种方法返回null.这里发生了什么?

D.R*_*.R. 7

这两种方法基本相同,请查看http://www.docjar.com/html/api/java/io/File.java.html以获取详细信息.

  • 同样的...除了`listFiles()`方法返回`File []`,而`list()`方法只返回文件*names*(即`String []`). (2认同)