List of files under a directory

I want to get list of files under a directory.

I want only the list of files and not the sub directories.

File dir =new File(sourceDir);

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++)

{

String filename = children[i];

File file =new File(filename);

if (file.isFile())

System.out.println(filename +" is a file");

else

System.out.println(filename +" is a dir");

}//for loop

}//else loop

Above code outputs "is a dir" for both files and directories. How can I find if a file is a file?>

[1321 byte] By [hardworkpaysa] at [2007-11-27 8:18:25]
# 1

You've already answered your own question.

File file = new File(filename) ;

if(file.isFile()){

// It's a file

}

There's more information available but that's the basics of it. I would suggest reading the api and related tutorials available from Sun.

PS.

puckstopper31a at 2007-7-12 20:03:58 > top of Java-index,Java Essentials,Java Programming...
# 2
There's probably something wrong with the way you're building the File from the String.Rather than list(), use listFiles(). You might also want to consider sticking that logic in a FileFilter and calling listFiles(FileFilter).
jverda at 2007-7-12 20:03:58 > top of Java-index,Java Essentials,Java Programming...
# 3
file.isfile() does not return true for files.Thats my problem.
hardworkpaysa at 2007-7-12 20:03:58 > top of Java-index,Java Essentials,Java Programming...
# 4

Thanks jverd.

I got a clue from your post.

Instead of

String filename = children[i];

File file = new File(filename);

I tried

String filename = children[i];

File file = new File(sourceDir + "\\" + filename);

I gave the complete path of the file instead of just the file name.

Now it correctly recognizes files and directories.

Thanks!

hardworkpaysa at 2007-7-12 20:03:58 > top of Java-index,Java Essentials,Java Programming...
# 5
Yes it does. Your problem is what you're passing in.Garbage in, garbage out.
armalcolma at 2007-7-12 20:03:58 > top of Java-index,Java Essentials,Java Programming...
# 6

> Thanks jverd.

>

> I got a clue from your post.

>

> Instead of

> > String filename = children[i];

> File file = new File(filename);

>

>

> I tried

> > String filename = children[i];

> File file = new File(sourceDir + "\\" + filename);

>

>

> I gave the complete path of the file instead of just

> the file name.

>

> Now it correctly recognizes files and directories.

>

> Thanks!

You're still doing it wrong. Use listFiles(), not list(). You're just making it more complicated.

jverda at 2007-7-12 20:03:58 > top of Java-index,Java Essentials,Java Programming...
# 7
> file.isfile() does not return true for files.> Yes it does.
jverda at 2007-7-12 20:03:58 > top of Java-index,Java Essentials,Java Programming...