i need to find all the files in the directory and sub directory that have a text file..within this text file there is a string called average with some value.. the code below works fine for a single directory...but i need to find the same text files in the sub directory .....can someone please help in how to traverse within the sub directories..

import java.io.*; 
import java.util.*; 
import java.io.FileWriter; 
import java.io.IOException; 
  //chets pgm
public class GenerateCsv 
{ 
   public static void main(String [] args) 
   {    
           generateCsvFile("C:\\DiffxNs.csv"); //creation of csv file 
   } 
  
   private static void generateCsvFile(String sFileName) 
        { 
                try 
                { 
                    FileWriter writer = new FileWriter(sFileName); 
            //FileInputStream fstream = new FileInputStream("C:\\Projects\\Broker\\result-parse\\results\\1kb\\Sub.txt");//extraction of txt file
            
			String dirLocation = "C:\\Projects\\Broker\\AIX\\IBMLabTests_Mar12\\Non-Pers_Pers_Result_AIX_Set2\\Non-Pers_Pers_Result_AIX_Set2\\DurableVsNonDurable\\Plain\\Durable\\Persistent\\Sub";//change path here
            File dir = new File("C:\\Projects\\Broker\\AIX\\IBMLabTests_Mar12\\Non-Pers_Pers_Result_AIX_Set2\\Non-Pers_Pers_Result_AIX_Set2\\DurableVsNonDurable\\Plain\\Durable\\Persistent\\Sub"); //COUNT of number of files 
            String[] children = dir.list(); 
                         					
						int count=0; 
                        for (int i=0; i<children.length; i++) 
                        { // Get filename of file or directory 
                        String filename = children[i]; 
                
                        String NewDir = dirLocation +"\\"+filename;
                        FileInputStream fstream = new FileInputStream(NewDir);
						DataInputStream in = new DataInputStream(fstream); 
                        BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
    
                   String strLine; 
     
    //Read File Line By Line 
    
                        
                        
                        
                        
                        
                        
                while ((strLine = br.readLine()) != null)  
     { 
      // Print the content on the console 
      //System.out.println (strLine); 
    
     String start = "average";   //string to be searched 
     if(i==0)
	 {
	 
 
   if (strLine.startsWith(start)) 
      { 
      writer.append("SI.NO");
	  writer.append(',');
	  writer.append("AVERAGE"); 
      writer.append(','); 
      writer.append("FILENAME"); 
      writer.append('\n'); 
	  count = count+1;
	  String aString = Integer.toString(count);
	  writer.append(aString);
	  writer.append(',');
	  String value = strLine;  
	  value=strLine.substring(14);
	  writer.append(value); 
      writer.append(','); 	  
      writer.append(children[i]);
	  }
	   else 
      
     { 
                System.out.println("nope"); 
      } 
	  
	  }
	  else
	  {
	  if (strLine.startsWith(start)) 
      { 
	    writer.append('\n'); 
       //writer.append(strLine); 
	   count = count+1;
	  String aString = Integer.toString(count);
	  writer.append(aString);
	  writer.append(',');
	  String value = strLine;  
	  value=strLine.substring(14);
	  writer.append(value); 
      writer.append(','); 
	  writer.append(children[i]);
	  }	
 else 
      
     { 
                System.out.println("nope"); 
      } 	  
      //writer.append(','); 
          //writer.append(strLine); 
	}
     
   
 
    
 
      }//Close the input stream 
    
 
 
     in.close(); 
            
                } 
				    
              System.out.println("Your file has been written"); 
                        writer.flush(); 
                        writer.close();
                
        }
             
						
                        //System.out.println(NewDir); 
                        //System.out.println(count); 
                        catch(Exception e) 
                { 
                 e.printStackTrace(); 
                } 
						} 
                       // count=count+1; 
                        
    // Get the object of DataInputStream 
    
}

Edited 6 Years Ago by peter_budo: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks)

First of all don't use the list() method because it doesn't return the full path and you forced to do this:

String NewDir = dirLocation +"\\"+filename;

Try this:

public void method(File dir) {

File [] children = dir.listFiles(); 

for (int i=0;i<children.length;i++) {
   if (children[i].isFile()) {
       BufferedReader reader = null;
       try {
              // read the file
              reader = ...;
       } catch (Exception e) {
            System.out.println(e.getMessage());
       } finally {
            try {
               close(); // close the readers you used to read the file (BufferedReader and so on)
           } catch (Exception e) {}
       }
   } else if (children[i].isDirectory()) {
             method(children[i]); // recursive call
   }
}

}

You can also check if the file is a .txt file before reading it:

public isTxt(File file) {

String name = file.toString();
int length = name.length;

if (length<=3) return false;

return name.subString(length-3, length).equalsIgnoreCase("txt");
}

And next time use code tags. Press the (code) button when creating a new post.

Edited 3 Years Ago by mike_2000_17: Fixed formatting

thanks for the quick reply..really appreciate it but i have some doubts ..can u pls help me out

public void method(File dir) {

do i pass my root directory over here..

thanks for the quick reply..really appreciate it but i have some doubts ..can u pls help me out

public void method(File dir) {

do i pass my root directory over here..

That method gets all the Files under the input directory. If it is a text file then it reads it, if it is a folder then it calls it self in order to read the Files under that directory.

Look at the code. With what was given it is up to you to understand it

thanks man..i did this it worked....

import java.io.*; 
import java.util.*; 
import java.io.FileWriter; 
import java.io.IOException; 

public class Dirtrav
{
public static void main(String args[])
{
      System.out.println("hello");
   // String rootDir="C:\\Projects\\PerfBVT'\\W6_TopicVsQueue_8.2.0.0.74_040110\\";
      File directory = new File("C:\\resultsexp");
      identifydir(directory); 

}  
	
	//File directory = new File("C:\\Projects\\PerfBVT'\\W6_TopicVsQueue_8.2.0.0.74_040110\\");  
     

public static void identifydir(File di)
 {
	 File[] files = di.listFiles();
	  //File file = new File();
	 if (! di.exists()) 
    {
	 System.out.println("Invalid path");
	 return;
	}
	if (di.isDirectory()) 
    {
	//String[] children = file.list();
	//System.out.println(children);
	
       	 for (int i = 0; i < files.length; i++)  
         {  
         //Print out the name of files in the directory  
         //System.out.println(files[index].toString());  
           System.out.println(files.length);
		   System.out.println(files[i]);
		   di=files[i];
		   identifydir(di);
		 }  
	    
	
	  }
    
 }
}
This question has already been answered. Start a new discussion instead.