如何在jtree中只列出非隐藏和非系统文件 [英] How to list only non hidden and non system file in jtree
问题描述
File f = new File(C:/);
文件fList [] = f.listFiles();
当我使用它时,会列出所有系统文件以及隐藏文件。
$ b
,导致空指针异常当我用它来显示在jTree中是这样的:
文件fList [] = f.listFiles();
for(int i = 0; i
$ b $ p
$ b $ p我该怎么做, strong> NullPointerException ,仅在jTree中显示非隐藏和非系统文件?
对于隐藏文件执行此操作:
文件root = new File(yourDirectory);
File [] files = root.listFiles(new FileFilter(){
@Override
public boolean accept(File file){
return!file.isHidden();
}
});
这不会返回隐藏文件。
至于系统文件,我相信这是一个Windows概念,因此可能不被 File
界面支持试图成为系统独立。尽管如此,你可以使用命令行命令。
或者使用@Reimeus在他的答案中。
可能类似于
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是在Java 7中引入的。
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?
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.
这篇关于如何在jtree中只列出非隐藏和非系统文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!