Write a program for recursive Traverse?



Write a program for recursive Traverse?..

Answer / swet bhushan

to recursively traverse over files and folders by making use
of Java File API. Whether it is a folder or a file, both are
represented as a java.io.File object. For example, consider
the following code snippet,


File myFile = new File("C:\\myDocuments\\myFile.txt"); // Case 1
File myFolder = new File("C:\\myDocuments"); // Case 2

If both files and folders are represented as a single File
object, then how can we differentiate between a File and a
Folder? The File API provides convenient methods for
determining this in the form of File.isDirectory() and
File.isFile(). For example, in case 1, File.isDirectory()
and File.isFile() returns false and true respectively,
whereas for case 2, it is true and false.

For listing all the files in a particular directory, we can
use the File.listFiles() method. When operated on a folder,
it will return all the files in the File Array object. For
example, consider the following code snippet,


File myFolder = new File("C:\\myDocuments");
File allMyFolderObjects[] = myFolder.listFiles();

In the above case, if we have two files (say file1.txt and
file2.txt) and a folder (sub-folder) within myFolder, then
the size of allMyFolderObjects will be three. Using the
combination of the above methods we have seen, let us write
code to recursively traverse over a folder object. Given
below is the complete code for the same.

FolderTraversar.java


package tips.foldertraversal;

import java.io.File;

public class FolderTraversar {

private String indent = "";
private File originalFileObject;
private File fileObject;

public FolderTraversar(File fileObject)
{
this.originalFileObject = fileObject;
this.fileObject = fileObject;
}

public void traverse()
{
recursiveTraversal(fileObject);
}

public void recursiveTraversal(File fileObject){
if (fileObject.isDirectory()){
indent = getIndent(fileObject);
System.out.println(indent + fileObject.getName());

File allFiles[] = fileObject.listFiles();
for(File aFile : allFiles){
recursiveTraversal(aFile);
}
}else if (fileObject.isFile()){
System.out.println(indent + " " +
fileObject.getName());
}
}

private String getIndent(File fileObject)
{
String original = originalFileObject.getAbsolutePath();
String fileStr = fileObject.getAbsolutePath();
String subString =
fileStr.substring(original.length(),
fileStr.length());

String indent = "";
for(int index=0; index<subString.length(); index ++){
char aChar = subString.charAt(index);
if (aChar == File.separatorChar){
indent = indent + " ";
}
}
return indent;
}
}

The above class FolderTraverser accepts a Folder object that
we wish to traverse. Then, by calling the
FolderTraverser.traverse() method, the folder can be
traversed recursively. The implementation of traverse()
delegates the control to a private method by name
recursiveTraversal(). Initially we are checking whether the
File object is a folder by calling the File.isDirectory()
method. If so, we print the name of the folder and then
retrieves the content of the Folder by calling the
File.listFiles() method. The array is again recursively
traversed. Note that just to make the output meaningful, we
have calculated the indent of the variousfiles and folder
items to be displayed.

FolderTraversarTest.java


package tips.foldertraversal;

import java.io.File;

public class FolderTraversarTest {

public static void main(String[] args) {

String folderPath =
"F:\\Technical
Writings\\www.javabeat.net\\Tips\\AllSamples\\AllTips\\src\\tips";
FolderTraversar traversal = new FolderTraversar(new
File(folderPath));
traversal.traverse();
}
}

The output of the above client program is,


tips
eforloop
EnhancedForLoopTest.java
UDEForLoop.java
pattern
factory
Button.java
ButtonFactory.java
FactoryClient.java
LinuxButton.java
WindowsButton.java
singleton
MyConnection.java
MyConnectionConsumer.java
state
...
...

Is This Answer Correct ?    2 Yes 0 No

Post New Answer

More Core Java Interview Questions

What is a super method?

0 Answers  


Is break statement can be used as labels in java?

0 Answers  


What is this keyword in java?

0 Answers  


how can i take the inputs from users in java program?

7 Answers   Wipro,


What is overriding in java?

0 Answers  






Difference between Primary key and unique key?

4 Answers  


what is collatration?

0 Answers  


What is java used for?

0 Answers  


What is the middleware?

2 Answers  


Can we create our own wrapper class in java?

0 Answers  


class A{ m2(){ } } class B extends A{ m2(){ } } class c extends B{ m2(){ } } class my_class extends c{ m2(){ } pulic static void main(){ ...My_class a = new my_class(); super.super.super.m2(); is this is leagal if not find what is the legal procedure in order to call A's version of m2(); }

8 Answers   Logica CMG,


How 'java' got its name and what it stands for?

11 Answers   Wipro,


Categories