Java show files 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.

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.

Ads