我制作了一个 Tree 对象,该对象加载了目录中的文件。preVisistDirectory 迭代得更快,然后 visitFile 可以跟随填充树。我尝试构建一个变量,该变量在读取文件并创建树项以读取下一个目录后调用,但没有工作。任何人?
public static void main(String[] args) {
// getfiles(filepath,"*html");
System.out.println("Help -> setHelp() -> Path = " + filepath);
Display display = new Display();
Shell shell = new Shell(display, SWT.CLOSE | SWT.RESIZE);
shell.setText("Tree Object. ");
shell.setSize(400, 300);
final Tree tree = new Tree(shell, SWT.BORDER | SWT.SINGLE);
tree.setSize(290, 290);
try {
Files.walkFileTree(filepath, new SimpleFileVisitor<Path>() {
TreeItem parent, child;
int baselevel = filepath.getNameCount();
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
System.out.println("Help -> FileVisitResults -> DirectoryName = " + dir.getFileName().toString());
System.out.println("Help -> FileVisitResults -> Find files and Directories : " + dir.getName(0));
System.out.println("Help -> FileVisitResults -> nameCount : " + (dir.getNameCount() - baselevel));
System.out.println("Help -> FileVisitResults -> baselevel = : " + (dir.getNameCount() - baselevel));
if (dir.getNameCount() - baselevel + 1 > 1) {
if (dir.getNameCount() - baselevel == 1) {
parent = null;
}
if (parent != null) {
child = new TreeItem(parent, 0);
child.setText(dir.getFileName().toString());
parent = child;
}
if (parent == null) {
child = new TreeItem(tree, 0);
child.setText(dir.getFileName().toString());
parent = child;
}
}
return FileVisitResult.CONTINUE;
}
public FileVisitResult visitFile(Path dir,
BasicFileAttributes attrs) {
System.out.println("Help -> FileVisitResults -> FileName = " + dir);
if (dir.getNameCount() - baselevel + 1 > 1) {
if (dir.getNameCount() - baselevel == 1) {
parent = null;
}
if (parent != null) {
child = new TreeItem(parent, 0);
child.setText(dir.getFileName().toString());
}
if (parent == null) {
child = new TreeItem(tree, 0);
child.setText(dir.getFileName().toString());
}
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
回答:
没有例外,但是通过目录循环更快,然后文件可以添加到目录中。因此,当在 2 个文件之后要由 vistitFile 添加 5 个文件时,preDirectoryVisit 会将父目录设置为下一个目录,因此 visitFile 会跳过剩余的文件。
答案 2:
树使用 preVisitDirectory 方法加载目录,该方法在目录上迭代得更快,然后 visitFile 对文件进行迭代。因为找到的目录存储在父变量中,该变量用作父树项以将文件添加为子树项。