Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

traverse?

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic