迭代文件和目录以加载SWT树

时间:2012-10-18 10:20:43

标签: java swt

我制作了一个Tree对象,它载有来自目录的文件。 preVisistDirectory迭代速度更快,然后visitFile可以跟随填充树。 我尝试构建一个变量,在读取文件后调用它,并创建treeitem以读取下一个目录但不起作用。 任何人??

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迭代文件。因为找到的目录存储在父变量中,所以使用父树节来将文件添加为子树项目。

2 个答案:

答案 0 :(得分:2)

parentchild节点的概念并没有真正解决。我设法使用两个HashMap来完成它。一个用于目录,一个用于文件。这样,您可以轻松找到当前文件/目录的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();
}

正如您可以阅读here一样,遍历的顺序不能保证与文件管理器中的顺序相同。这就是我在将目录的子项添加到树之前收集目录的子项的原因。不需要对目录进行排序。

  

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

以下是树的外观:

enter image description here

这是文件夹结构:

enter image description here

答案 1 :(得分: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;
    }
     }