Share on Google+Share on Google+

Java show files in tree format

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 javax.swing.*;
import javax.swing.tree.*;

class FileTree {

	public static DefaultMutableTreeNode addTree(String dirname) {
		File file = new File(dirname);
		DefaultMutableTreeNode root = new DefaultMutableTreeNode();
		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:/"));

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


Posted on: September 8, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.