wood burning stoves 2.0*
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "traverse?" Watch "traverse?" New topic
Author

traverse?

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
Consider the following program used for browsing a directory structure:
import java.io.*;
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() ".
Sonir
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?
Ragu
Shivaji Marathe
Ranch Hand

Joined: Jan 11, 2002
Posts: 203
Sonir
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: traverse?