Checking and Reading Contents of a Directory in Java - Java
Home » Java

Checking and Reading Contents of a Directory in Java

25 November 2009 No Comment

Many applications require to check if the file being accessed is really a file or a directory. Also if it is a directory then you would need to traverse through the contents of directory. Here is the code snippet that shows how to do it. In addition to this you may have to handle exceptions. Also ensure the file is closed at the end of everything in finally block.

import java.io.File;

public class DirectoryCheck {

	public static void main(String[] args) {
		DirectoryCheck directoryCheck = new DirectoryCheck();
		directoryCheck.checkIfDirectory("C:\\Program Files");
		directoryCheck.checkIfDirectory("C:\\SampleFile.txt");
	}

	public boolean checkIfDirectory(String path){
		boolean result = false;

		File file = new File(path);
		result=file.isDirectory();
		System.out.println("Tell me if it is a file? ;" + result);
		if(result){
			File[] files = file.listFiles();
			for(File myFile : files){
				System.out.println("File is " + myFile.getName());
			}
		}
		return result;
	}
}

 

More Related Posts in Java

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.