Home Tutorial Java Io Display list of files from a directory using Java

 
 

Share on Google+Share on Google+
Display list of files from a directory using Java
Posted on: November 9, 2009 at 12:00 AM
Advertisement
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();
	}
}

Advertisement

Related Tags for Display list of files from a directory using Java:


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: November 9, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com