Display list of files from a directory using Java


 

Display list of files from a directory using Java

In this section, you will learn how to display the list of files of a particular directory or a sub directory.

In this section, you will learn how to display the list of files of a particular directory or a sub directory.

Display list of files from a directory using Java

In this section, you will learn how to display the list of files of a particular directory or a sub directory. For this purpose, we have specified a path.The method isDirectory() tests whether the specified path contains any directory and isFile() checks whether the specified path contains anny file.If it is having any directory then listFiles() method display the list of file names of that directory and if it is having any file then getName() method display their names. We have also showed the size of each file with the use of length() method.

Here is the code:

import java.io.*;

class Listing {
	String st = "";
	File file;
	File f;

	public Listing(File f) {
		this.file = f;
		this.f = f;
	}

	public void displayFiles() {
		findFiles(f);
	}

	public void findFiles(File f) {
		if (f.isDirectory()) {
			st = getFiles(f);
			System.out.println(st + f.getName());
			File files[] = f.listFiles();
			for (File ff : files) {
				findFiles(ff);
			}
		} else if (f.isFile()) {
			System.out.println(st + "  " + f.getName() + "           Size is: "
					+ f.length());
		}
	}

	private String getFiles(File f) {
		String originalPath = file.getAbsolutePath();
		String path = f.getAbsolutePath();
		String subString = path.substring(originalPath.length(), path.length());
		String st = "";
		for (int index = 0; index < subString.length(); index++) {
			char ch = subString.charAt(index);
			if (ch == File.separatorChar) {
				st = st + "  ";
			}
		}
		return st;
	}
}

public class ListAllFiles {
	public static void main(String[] args) {
		String p = "C:\\";
		Listing list = new Listing(new File(p));
		list.displayFiles();
	}
}

Ads