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?>
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.
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!
> 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 >
