Home Tutorial Java Core Files Java show files in tree format

 
 

Share on Google+Share on Google+
Java show files in tree format
Posted on: September 8, 2006 at 12:00 AM
Advertisement
In this section you will learn how to display the whole file system in tree format.

Java show files in tree format

In this section you will learn how to display the whole file system in tree format.

Description of code:

The java.swing* package introduces several useful classes and  methods. It is used in several applications. We have also used this package in our example. In the given example, we have used JTree class to show the whole files in a systematic way.

DefaultMutableTreeNode- This class provides operations for examining and modifying a node's parent and children and also perform operations to examine the tree.

isDirectory() method- This method of File class checks whether the specified file is a directory.

insert() method-  This method of DefaultMutableTreeNode class sets the child's parent to the node, and then add the child to the node's child array at index.

Here is the code:

import java.io.File;
import javax.swing.*;
import javax.swing.tree.*;

class FileTree {

	public static DefaultMutableTreeNode addTree(String dirname) {
		File file = new File(dirname);
		DefaultMutableTreeNode root = new DefaultMutableTreeNode();
		root.setUserObject(file.getName());
		if (file.isDirectory()) {
			File files[] = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				root.insert(addTree(files[i].getPath()), i);
			}
		}
		return (root);
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.setSize(300, 400);
		JTree tree = new JTree(addTree("C:/"));
		frame.add(tree);
		frame.setVisible(true);
	}
}

Through the above code, you can display your files in a systematic format.

Advertisement

Related Tags for Java show files in tree format:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 8, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com