File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes traverse? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "traverse?" Watch "traverse?" New topic


sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
Consider the following program used for browsing a directory structure:
class NaviTest
public static void traverseDir(File f) throws IOException
System.out.println(f.getCanonicalPath()); //1
if(f.isDirectory()) //2
File[] fls = f.listFiles(); //3
for(int i=0; i<fls.length; i++) traverseDir(fls[i]);
public static void main(String args[]) throws IOException
traverseDir( new File(args[0]) );
Which of the following statments are correct?
1)It will not compile because of //1
2)f.isDirectory() at //2 should be replaced with f.isDir()
3)f.listFiles() should be replaced with f.list()
4)It will compile as it is
5)It is a valid program that can browse through any given directory
Can any explain me..specially about "traverseDir() ".
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Well the method helps you to list the available files in the directory specified, provided the given argument or input is a directory
try this
compile this code and run
java NaviTest .
you will see all the files in your current directory if any?
Shivaji Marathe
Ranch Hand

Joined: Jan 11, 2002
Posts: 203
You can compile this class and then run it using the following code
Make sure you use a directory ( in place of C:\\temp ) that has few files (3-4)and few subdirectories ( 2-3) which also have 2-3 files each. Remember to use double backslah characters in the file path, because single backslash is an escape character.
If you follow the output of this program, you can easily understand what the method is doing.It is classic example of recursive method.

Hope this helps
I agree. Here's the link:
subject: traverse?
It's not a secret anymore!