Listing the Files or Subdirectories in a Directory

This example lists the files and subdirectories in a directory. To list all descendant files and subdirectories under a directory, see Traversing the Files and Directories Under a Directory.
File dir = new File("directoryName");

String[] children = dir.list();
if (children == null) {
    // Either dir does not exist or is not a directory
} else {
    for (int i=0; i<children.length; i++) {
        // Get filename of file or directory
        String filename = children[i];
    }
}

// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return !name.startsWith(".");
    }
};
children = dir.list(filter);


// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();

// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
    public boolean accept(File file) {
        return file.isDirectory();
    }
};
files = dir.listFiles(fileFilter);

Comments

17 Feb 2010 - 10:59am by Anonymous (not verified)

Would this work if I had the Java applet inserted into a webpage and use it to list all the directories?

19 Mar 2010 - 11:45am by luke (not verified)

Con il metodo list() la lista dei file non è ordinata(come c'è scritto sulle API) come è possibile farlo?...

16 Apr 2010 - 7:04am by Anonymous (not verified)

Thanks, this was almost too easy and allowed me to add a feature that I had been resisting. I also learned something new!

20 Jul 2010 - 6:51am by Anonymous (not verified)

Awesome! Thanks!

24 Aug 2010 - 8:31am by Anonymous (not verified)

Thanks....you da man!

25 Aug 2010 - 8:53am by IcyBlueRose (not verified)

This really did work fantastically! Plug it in, import java.io, plug in the dir name and go! It worked perfectly. So few things do! Thank you.

16 Nov 2010 - 10:29pm by Anonymous (not verified)

I am trying to do the same for listing the files in a Java applet & running it an an HTML but it is not working. Any suggestiongs for this?

17 Nov 2010 - 12:27pm by Flappa Jack (not verified)

@Anonymous Try using PHP instead <?php echo shellexec("ls") ?> for linux based servers

15 Jan 2011 - 9:00pm by Anonymous (not verified)

thanks so so so much, helped me so much with my final project

17 Feb 2011 - 7:36am by mistik1 (not verified)

@Anonymous
Remember that when dealing with Applets and java webstart file operations are probably going through the SecurityManager and without proper configuration will fail.

13 Mar 2011 - 10:39am by Anonymous (not verified)

Thanks! this helps me to much!

15 Mar 2011 - 10:29am by Anonymous (not verified)

<%
File dirfile = new File(config.getServletContext().getRealPath("/")) ;
String[] children = dirfile.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i" + children[i] + "");
}
}

%>

are returning half of the list . Any clue ?!

16 Mar 2011 - 9:03am by Anonymous (not verified)

I used this code to go recursivly through a directory and find .txt and .doc files. really neat.

12 May 2011 - 9:10pm by Deepak (not verified)

For getting all specific directories , subdirectories , child directories....
-----------------------------------------------------------------------------------------

import java.io.File;
import java.io.FileFilter;

public class GetChildDirectories {

static File dir = new File("/home/deepak");

private static void getAllDirsAlone() {
if(dir.isDirectory()) {
File[] files = dir.listFiles();
for (int i=0; i>"+files[i]+"\ndir alone -->>"+files[i].getName());
dir = files[i];
getAllDirsAlone();
}
}
}

public static void main(String[] args) {
getAllDirsAlone();
}

}

Output:
Path::-->>/home/deepak/hai
dir alone -->>hai
Path::-->>/home/deepak/hai/hihi/hai
dir alone -->>hai
Path::-->>/home/deepak/myfolder2/hai
dir alone -->>hai

29 Jun 2011 - 11:47pm by baby photo books (not verified)

I would love to know more about this type of codes. Thanks for sharing this.

5 Jul 2011 - 10:22am by note pads (not verified)

There are so many things to memorize in here most specially the codes.

16 Jul 2011 - 2:56am by Anonymous (not verified)

Thanks very much.

20 Jul 2011 - 1:58am by Anonymous (not verified)

Finally something that works. Thanks up-loader for spending time to save my time.

27 Jul 2011 - 7:02pm by Anonymous (not verified)

Why not

if (children != null) {

This works for me

31 Aug 2011 - 6:54am by Anonymous (not verified)

Thank you very much. Much easier than I though it would be.

4 Sep 2011 - 6:38am by iphoness (not verified)

Thanks for the review.
it’s very interesting and full of handy features.

20 Oct 2011 - 8:25pm by replica designer handbags (not verified)

unglasses the deterioration in environmental conditions and competition more intense human situations,fake Oakley Sunglasses people asked to relax close to nature in the tense mood in the competition, MBT shoes will gradually spread outdoor up.
Replica Designer Handbags The popularity of outdoor sports shoes to mountaineering,Cheap Replica Handbags rock climbing, camping and other adventure sports most widely used.replica Coach handbags These countries on the movement itself is very popular in Europe and America,Coach designer handbags and these movements have formed a complete business model.Replica Chanel Handbags The number of new projects in China is still not fully developed and cheap Gucci Handbags
Industry, outdoor products backpack. cheap Louis Vuitton designer handbags on sale silver is a sport many years ago,Cheap Coach Purses Online now it is just to refine it. Take the camping adventure, mountaineering, rock climbing,Replica Coach 2011 Handbags the earliest dating back to 18th century Europe. Before that,cheap Chanel Sunglasses people do not like close to the mountains, with a total
Think it is the devil the same place,replica designer handbags until the 18th century,coach handbags outlet some missionaries began to missionary,replica Coach handbags had through the mountains.replica Coach Backpack Scientists into the mountains,hobo international handbags do some ecological studies,coach handbags 2011 outlet in addition to these people, there are some due thanks to the industrial revolution,designer handbags for less thanks to the formation of industrial
And entrepreneurs and other new replica sunglasses, these people have a certain amount of money after a while in pursuit of another cheap designer sunglasses, began climbing as an alternative to leisure. At the time, Ray-Ban Aviator Sunglasses, the first board (a Ray-Ban Wayfarer Sunglasses is the first human ascent) on the pursuit of all climbers
Goals,Ray-Ban Clubmaster Sunglasses when those in the Alps, the more gentle and easy to reach the hills have been registered after the first,Ray-Ban JUNIOR Sunglasses the rest is very difficult to have a big hill. Climbers at the time, in order to overcome these snow ice rock terrain, and then develop a set of technologies. Only this time Both technically and equipment are still quite primitive, outdoor advertising works,Moncler Pas Cher until after World War II, in order to meet the special needs of the terrain on operations, the military began to develop these techniques,Doudoune Moncler Femme rock climbing and camping has been gradually taking shape, The real form of physical items classification

7 Nov 2011 - 9:43pm by mortgage loans (not verified)

I strictly recommend not to hold back until you get big sum of cash to order different goods! You can get the credit loans or just student loan and feel yourself fine

25 Dec 2011 - 6:04pm by cheap shoes (not verified)

Thanks for your opinion. discount shoes I totally like with it.I like cheap designer shoes as well and someone is looking for cheap shoes People usually prefer fake designer shoes, especially when they visit some shoes outlet. In some areas,people like to wholesale clothing. They will find some store doing very cheap or discounted Chanel shoes outlet. Certainly, is a good way to earn money. designer shoes outlet

1 Jan 2012 - 8:09am by Pharmf398 (not verified)

Hello! ccbebbe interesting ccbebbe site! I'm really like it! Very, very ccbebbe good!

1 Jan 2012 - 8:13am by Pharme347 (not verified)

Very nice site!

25 Jan 2012 - 1:21pm by Pharma135 (not verified)

Hello! ackkeka interesting ackkeka site! I'm really like it! Very, very ackkeka good!

28 Mar 2012 - 4:57am by Paper Writing service (not verified)

discount shoes I totally like with it.I like cheap designer shoes as well and someone is looking for cheap shoes People usually prefer fake designer shoes, especially when they visit some shoes outlet. In some areas,people like to wholesale clothing.

28 Mar 2012 - 5:59am by Vikram Pawar (not verified)

Thanks.........

8 Apr 2012 - 4:01am by Hitch Mounted Bike Rack (not verified)

After study a number of of the posts in your web site now, and I truly like your efforts. I bookmarked it to my bookmark website listing and shall be checking back soon.
Many Thanks guys :)

12 May 2012 - 4:40am by Anonymous (not verified)

I have illegal start of type errors... Why?

16 May 2012 - 7:34am by William Blanco-Tarniella (not verified)

The code did not work for my situation. I came up with this not much time to think or research but I hope it helps someone in the future.

import java.io.File;

public class Files {

public static void main(String[] args) {
int indentlvl = 0;
File dir = new File("C:\\Users\\wblanco\\Documents\\Workspaces\\PR-WSN\\PR-WSN");
out(dir,indentlvl);
}
private static void out(File dir, int indentlvl) {
for(File f : dir.listFiles()) {
if(f.isDirectory()) {
out(f, indentlvl+1); //Recursive Call
//Indent
for(int i = 0; i <= indentlvl; i++) System.out.print("\t");
System.out.println(f.getName());
}
}
}
}

16 May 2012 - 7:38am by William Blanco-Tarniella (not verified)

Error! In The previous code the curly braces of the if(f.isDirectory()) {
out(f, indentlvl+1); //Recursive Call should end right after the call

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.