1

我制作了一个 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 对文件进行迭代。因为找到的目录存储在父变量中,该变量用作父树项以将文件添加为子树项。

4

2 回答 2

2

您的parentandchild节点的概念并没有真正奏效。我设法使用两个HashMaps 让它工作。一个用于目录,一个用于文件。这样,您可以轻松找到parent当前文件/目录的:

private static Map<String, TreeItem> nodes = new HashMap<>();
private static Map<TreeItem, List<String>> children = new HashMap<>();

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    final Tree tree = new Tree(shell, SWT.BORDER);

    Path path = FileSystems.getDefault().getPath("/home/baz/TestFolder/", new String[] {});
    try {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
            {
                TreeItem parent = nodes.get(dir.getParent().toString());
                TreeItem item = null;
                if(parent == null)
                {
                    item = new TreeItem(tree, SWT.NONE);
                }
                else
                {
                    item = new TreeItem(parent, SWT.NONE);
                }
                item.setText(dir.getFileName().toString());

                nodes.put(dir.toString(), item);

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path dir, BasicFileAttributes attrs)
            {
                TreeItem parent = nodes.get(dir.getParent().toString());

                if(children.get(parent) == null)
                    children.put(parent, new ArrayList<String>());

                children.get(parent).add(dir.getFileName().toString());

                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    for(TreeItem parent : children.keySet())
    {
        for(String child : children.get(parent))
        {
            TreeItem item = new TreeItem(parent, SWT.NONE);
            item.setText(child);
        }

    }

    tree.layout();
    nodes = null;
    children = null;

    shell.setSize(400,400);
    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }

    display.dispose();
}

正如您在此处所读到的,不能保证遍历的顺序与您的文件管理器中的相同。这就是为什么我在将目录的子项添加到树之前收集它们的原因。目录虽然不需要排序。

文件树首先遍历深度,但您不能对访问子目录的迭代顺序做出任何假设。

这是树的外观:

在此处输入图像描述

这是文件夹结构:

在此处输入图像描述

于 2012-10-19T09:26:42.283 回答
0

在创建树项目时通过向树项目添加数据来完成代码。在树中单击时,数据用于在浏览器面板中打开文件。

    package object;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URI;
    import java.net.URL;
    import java.nio.file.FileSystems;
    import java.nio.file.FileVisitResult;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.SimpleFileVisitor;
    import java.nio.file.attribute.BasicFileAttributes;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.browser.Browser;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Event;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.ToolBar;
    import org.eclipse.swt.widgets.ToolItem;
    import org.eclipse.swt.widgets.Tree;
    import org.eclipse.swt.widgets.TreeItem;


    public class Helpsystem {
    private static Tree tree;
    private static Browser browser; 
    private static Map<String, TreeItem> nodes = new HashMap<>();
    private static Map<TreeItem, List<Path>> children = new HashMap<>();
    private static String lang="gb";
    private static GridData griddatatree,griddatabrowser,griddatatoolbar;
    static Path path = FileSystems.getDefault().getPath("html/Help/"+lang+"/",new String[] {});

    public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    GridLayout gridlayout = new GridLayout(5,true);
        shell.setLayout(gridlayout);
    ToolBar toolbar = new ToolBar(shell, SWT.BORDER);
            toolbar.setSize(200, 30);

     griddatatoolbar = new GridData(SWT.FILL,SWT.FILL,true,false);
           griddatatoolbar.horizontalSpan=5;

    toolbar.setLayoutData(griddatatoolbar);
    ToolItem home = new ToolItem(toolbar,SWT.PUSH);
            home.setText("Home.");
            home.setToolTipText("Return to index.");
            home.addSelectionListener(new SelectionAdapter(){
                public void widgetSelected(SelectionEvent e){
                    browser.setText("loadPage(indexUrl.toURL())");
                            }});    
    ToolItem back = new ToolItem(toolbar,SWT.PUSH);
            back.setText("Back.");
            back.setEnabled(true);
            back.setToolTipText("Previous page.");
            back.addSelectionListener(new SelectionAdapter(){
                public void widgetSelected(SelectionEvent e){
                    browser.back();         
                            }});    

        tree = new Tree(shell, SWT.BORDER);
        griddatatree = new GridData(SWT.FILL,SWT.FILL,true,true);
                     griddatatree.horizontalSpan=2;
                     tree.setLayoutData(griddatatree);

        tree.addListener(SWT.Selection,new Listener(){
           public void handleEvent(Event e){
                      for(TreeItem selection:tree.getSelection()){ 
                               if(selection.getData()==null){return;};
                     try {
                             URL url=  ((URI) selection.getData()).toURL();
                             browser.setText(loadPage(url));

                      }  catch (MalformedURLException e1) { e1.printStackTrace(); }
                   }
                }
           });           

        browser = new Browser(shell, 0 );
        griddatabrowser = new GridData(SWT.FILL,SWT.FILL,true,true);
                griddatabrowser.horizontalSpan=3;
        browser.setLayoutData(griddatabrowser);


    try {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
            {
                TreeItem parent = nodes.get(dir.getParent().toString());
                TreeItem item = null;
                if(parent == null)
                {
                    item = new TreeItem(tree, SWT.NONE);
                }
                else
                {
                    item = new TreeItem(parent, SWT.NONE);
                }
                item.setText(dir.getFileName().toString());

                nodes.put(dir.toString(), item);

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path dir, BasicFileAttributes attrs)
            {
                TreeItem parent = nodes.get(dir.getParent().toString());

                if(children.get(parent) == null)
                    children.put(parent, new ArrayList<Path>());

                children.get(parent).add(dir);

                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    for(TreeItem parent : children.keySet())
    {
        for(Path child : children.get(parent))
        {
            TreeItem item = new TreeItem(parent, SWT.NONE);
            item.setText(child.getFileName().toString());
            item.setData(child.toUri());

        }

    }




    nodes = null;
    children = null;
    shell.setSize(800,600);
    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }

    display.dispose();
    }
    protected static String loadPage(URL helppageUrl) {
        String str = null;
       try {
          InputStream is = helppageUrl.openStream();
          InputStreamReader r = new InputStreamReader(is);
          char[] buffer = new char[32];
          StringBuffer sb = new StringBuffer();
          int count;
          while ((count = r.read(buffer, 0, buffer.length)) > -1) {
            sb.append(buffer, 0, count);
          }
          str = sb.toString();
          is.close();
          r.close();
        } catch (IOException ex) {
          str = "Failed to load text";
        }
         return str;
    }
     }
于 2012-10-21T13:26:51.343 回答