Checking and Reading Contents of a Directory in Java

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;
	}
}
  • Share/Bookmark
Java

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Leave Comment

(required)

(required)