File System Viewer In Java - Online Article

Objective

The purpose of this tutorial is to demonstrate the efficiency and power of Java with the "Platform Independency" and lesson to the persons who thought that Java is less powerful then .NET.

Before read this tutorial you have some prior knowledge of Java I/O and Swing/AWT packages with some programming experience.

Overview

Here is a code sample which creates the file system viewer. The main method calls the constructer of "FileSystemFrame "class with the address/location of file/drive which creates the File System of given file location. To get the view of file system you must change the location/address, here I use the C:\ on windows. In this code I use the swing components for GUI but it can be replaced by AWT components.

To test this code you must installed the JDK 1.5 or above. Alternatively, you can download it here

Source Code

import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;


public class FileSystemFrame extends JFrame
{
	//Creates the instances of JTree, FileSystemModel and JTextArea.
	private JTree fileTree;
	private FileSystemModel fileSystemModel;
	private JTextArea fileDetailsTextArea = new JTextArea();
	
	public FileSystemFrame(String directory)
	{
		//Title of window.
		super("RKG - FileSystem Viewer");

		//Create instance of FileSystemModel and make the tree.
		fileSystemModel = new FileSystemModel(new File(directory));
		fileTree = new JTree(fileSystemModel);

		//Making right pane non-editable and left pane editable.
		fileDetailsTextArea.setEditable(false);
		fileTree.setEditable(true);

		//Add action event on tree components.
		fileTree.addTreeSelectionListener(new TreeSelectionListener()
		{
			//This method gets the changed value of Tree.
			public void valueChanged(TreeSelectionEvent event)
			{
				File file = (File) fileTree.getLastSelectedPathComponent();
				fileDetailsTextArea.setText(getFileDetails(file));
			}
		});

		//Ctreates the instance of JSplitpane and set the configuration.
		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
									true, new JScrollPane(fileTree), new JScrollPane(fileDetailsTextArea));
       getContentPane().add(splitPane);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(640, 480);
		setVisible(true);
	}

	//This method get the details of input file or location.
	private String getFileDetails(File file)
	{
		if (file == null)
		{
			return "";
		}

		//Displays the properties of file/directory in the right pane.
		StringBuffer buffer = new StringBuffer();
		buffer.append("Total Space in the partition is: " + file.getTotalSpace() + " Bytes"+"\n");
		buffer.append("Free Space in the partition is: " + file.getFreeSpace() + " Bytes"+"\n");
		buffer.append("The usable space in the partition is: " + file.getUsableSpace() + " Bytes"+"\n");
		buffer.append("Name: " + file.getName() + "\n"); buffer.append("Path: " + file.getPath() + "\n");
		buffer.append("Absolute Path is: " + file.getAbsolutePath() + "\n");
		buffer.append("Parent: " + file.getParent() + "\n");
		buffer.append("Size: " + file.length() + " Bytes"+"\n");

		if(file.canRead())
			buffer.append("Readable file"+"\n");
		else
			buffer.append("Non-Readable file"+"\n");
		if(file.canWrite())
			buffer.append("Writeable file"+"\n");
		else
			buffer.append("Non-Writeable file"+"\n");
		if(file.isHidden())
			buffer.append("It is a hidden file"+"\n");
		return buffer.toString();
	}
	public static void main(String args[])
	{
		//Address or location of file or drive for which File System to be made.
		FileSystemFrame FileSystem = new FileSystemFrame("C:\\");
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			SwingUtilities.updateComponentTreeUI(FileSystem);
		}
		catch (Exception ex)
		{
			Logger.getLogger(FileSystemFrame.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
}
//This class creates the model of input file system with
//the implementation of Java "TreeModel".
class FileSystemModel implements TreeModel
{
		//Ctreates the instances of File and Vector.
		private File root;
		private Vector listeners = new Vector();
		//Contructor.
		public FileSystemModel(File rootDirectory)
		{
			root = rootDirectory;
		}
		//This is overidden method of Java TreeModel interface which gives the root of input file.
		public Object getRoot()
		{
			return root;
		}
		//This is overridden method of Java TreeModel inteface and gives the
		//details of child.
		public Object getChild(Object parent, int index)
		{
			File directory = (File) parent;
			String[] children = directory.list();
			return new TreeFile(directory, children[index]);
		}
		//This method gives the number of childs for Tree(File System).
		public int getChildCount(Object parent)
		{
			File file = (File) parent;
			if (file.isDirectory())
			{
				String[] fileList = file.list();
				if (fileList != null)
				{
					return file.list().length;
				}
			}
			return 0;
		}
		//This method gives the details of tree node that it is leaf or not.
		//It is also check that node is file or not.
		public boolean isLeaf(Object node)
		{
			File file = (File) node;
			return file.isFile();
		}
		//This method create the structure of tree.
		public int getIndexOfChild(Object parent, Object child)
		{
			File directory = (File) parent;
			File file = (File) child;
			String[] children = directory.list();
			for (int i = 0; i < children.length; i++)
			{
				if (file.getName().equals(children[i]))
				{
					return i;
				}
			}
			return -1;
		}
		//This method observes the changes occured in the tree such as: Renaming of file/directory.
		public void valueForPathChanged(TreePath path, Object value)
		{
			File oldFile = (File) path.getLastPathComponent();
			String fileParentPath = oldFile.getParent();
			String newFileName = (String) value;
			File targetFile = new File(fileParentPath, newFileName);
			oldFile.renameTo(targetFile);
			File parent = new File(fileParentPath);
			int[] changedChildrenIndices = {getIndexOfChild(parent, targetFile)
		};
		Object[] changedChildren = {targetFile};
		fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);
	}
	//This method observes the change in the nodes of Tree(File System).
	private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children)
	{
		TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
		Iterator iterator = listeners.iterator();
		TreeModelListener listener = null;
		while (iterator.hasNext())
		{
			listener = (TreeModelListener) iterator.next();
			listener.treeNodesChanged(event);
		}
	}
	public void addTreeModelListener(TreeModelListener listener)
	{
		listeners.add(listener);
	}
	public void removeTreeModelListener(TreeModelListener listener)
	{
		listeners.remove(listener);
	}
	//This class make the tree file structure for File System.
	private class TreeFile extends File
	{
		public TreeFile(File parent, String child)
		{
			super(parent, child);
		}
		public String toString()
		{
			return getName();
		}
	}
} 

Image1

Screenshot of running application

About the Author:

No further information.




Comments

No comment yet. Be the first to post a comment.