How to List Files and Sub-directories in a Directory in Java?

DeeKay March 6, 2012 at 12:17 am · java.io

Below java code shows how to list files and sub-directories in a directory –

 

/****************************************************************************************
* Created on 03-2012 Copyright(c) http://kodehelp.com All Rights Reserved.
****************************************************************************************/
package com.kodehelp.javaio;

import java.io.File;

/**
* Created by http://kodehelp.com
* Date: 03/05/2012
*/
public class ListFileAndDirectory {

public static void main(String[] args) {
File dir = new File(“c:/tmp”);
String[] children = dir.list();
if (children == null) {
System.out.println(“does not exist or is not a directory”);
} else {
for (int i = 0; i < children.length; i++) { String filename = children[i]; System.out.println(filename); } }}} [/java]