javaswingfile-iojtreefilefilter

How to list only non hidden and non system file in jtree


File f=new File("C:/");
File fList[] = f.listFiles();

When i use this it list all system file as well as hidden files.

and this cause null pointer exception when i use it to show in jTree like this:

 public void getList(DefaultMutableTreeNode node, File f) {
 if(f.isDirectory()) {
     DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
     node.add(child);
     File fList[] = f.listFiles();
     for(int i = 0; i  < fList.length; i++)
         getList(child, fList[i]);
     }
}

What should i do so that it do not give NullPointerException and show only non hidden and non system files in jTree?


Solution

  • Do this for hidden files:

    File root = new File(yourDirectory);
    File[] files = root.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return !file.isHidden();
        }
    });
    

    This will not return hidden files.

    As for system files, I believe that is a Windows concept and therefore might not be supported by File interface that tries to be system independent. You can use Command line commands though, if those exist.

    Or use what @Reimeus had in his answer.

    Possibly like

        File root = new File("C:\\");
    
        File[] files = root.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                Path path = Paths.get(file.getAbsolutePath());
                DosFileAttributes dfa;
                try {
                    dfa = Files.readAttributes(path, DosFileAttributes.class);
                } catch (IOException e) {
                    // bad practice
                    return false;
                }
                return (!dfa.isHidden() && !dfa.isSystem());
            }
        });
    

    DosFileAttributes was introduced in Java 7.