Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8704977
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T03:14:28+00:00 2026-06-13T03:14:28+00:00

I made a Tree object which is loaded with files from a directory. preVisistDirectory

  • 0

I made a Tree object which is loaded with files from a directory.
preVisistDirectory iterates faster then visitFile can follow to fill the tree.
I tried to build a variable which is called after the files are read and the treeitem created to read the next directory but didn’t work.
Anyone?

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();
}

Answer:
There are no exceptions, but loops faster through the directories then the files can be added to the directories. So when there are 5 files to be added by vistitFile after 2 files the preDirectoryVisit sets parent to the next directory so visitFile skips the remaining files.

Answer 2:
The tree loads the directories with preVisitDirectory method wich itterates faster over over the directories then visitFile iterates over the files. Because the found directory is stored in the parent variable which is used ass the parent treeitem to a add the file as a child treeitem.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T03:14:29+00:00Added an answer on June 13, 2026 at 3:14 am

    Your concept of parent and child node doesn’t really work out. I managed to get it working using two HashMaps. One for the directories and one for the files. This way, you can easily find the parent of your current file/directory:

    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();
    }
    

    As you can read here the order of traversal is not guaranteed to be the same as in your file manager. This is why I collect the children of a directory before adding them to the tree. The directories needn’t be sorted though.

    A file tree is walked depth first, but you cannot make any assumptions about the iteration order that subdirectories are visited.

    Here is how the tree looks:

    enter image description here

    And this is the folder structure:

    enter image description here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I had to populate a tree view for which i have made a custom
I have made a tree structure using c and used it for storing some
I've made my own tree data structure via classes. Now I'm stuck with really
First of all my tree is made up of nodes that look like this:
I made an iphone app to capture image from camera and to set that
I made a Web service in which I have a function to count some
i made an .xib file and added my buttons and labels. Then I created
In my application,I want to display some static files(.html,.htm,.txt) which will be uploaded by
I've made a generic extension method that executes an action on an object and
i have made an binary tree, and im trying to make an postorder traversal.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.