Solved

How to read files in nested directories in Java

Posted on 2011-03-01
7
364 Views
Last Modified: 2012-05-11
Hello,

This is the code I have so far. It works when I have a top level folder passed through dir.

i.e.  C:/Input

With multiple nested folders, the code will need to work without knowing the number of the folders and files within the folders.

String[] list = getFolderList(inputdir);

public String[] getFolderList(String inputDir)
    {
        File file = new File(inputDir);

        if (!file.exists())
        {
            log.error(inputDir + " file doesnot exist");
            return null;
        }
        if (!file.isDirectory())
        {
            log.error(inputDir + " is not a directory");
            return null;
        }

        return file.list();
    }

Open in new window


Thanks
0
Comment
Question by:AndyC1000
  • 5
  • 2
7 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35012984
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35012988
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35013064
Once you discover that you are dealing with the file iafter the "else" in this snippet below,
you can do whatever you need with it - say getAbsolutePath() and
collect all pathnamse of all files into ArrayList for future
printing, or you can analize file names for certain type
and read something from some of the files you are looking for.
So this mnay be a good beginning for any amnipulations with files and folders
inside specified folder  

public static void traverse(File directory)
{
   // Get all files in directory

   File[] files = directory.listFiles();
   for (File file : files)
   {
      if (file.isDirectory())
      {
         // Its a directory so (recursively) traverse it

         traverse(file);
      }
      else
      {
         // its a file, do any processing you require here
      }
   }
}

Open in new window

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:AndyC1000
ID: 35013189
Thanks.

I have a method called processFiles how to create a list of files where the program can find the location, retaining the folders etc when I will only have the directory path.

private void processFiles(String inputdir) throws IOException
    {
        String[] list = getFolderList(inputdir);

      
        if (list != null)
        {
             for (int i = 0; i < list.length; i++)
            {
                File file = new File(list[i]);

                System.out.println("File: " + file);

                if (getFileType(file.getName()) != null)
                {
                    log.info("Now reading file " + file);

                    parser = new FileParser();
                    parser.openFile(file, inputdir);
                    parser.readFile();
                } 
                else
                {
                    log.info("Skipping directory " + file);
                    continue;
                }
            }

         } else
        {
            log.error("Folder list is null");
            throw new NullPointerException("Folder list is null");
        }
    }

Open in new window


public String[] getFolderList(String inputDir)
    {
        File file = new File(inputDir);

        if (!file.exists())
        {
            log.error(inputDir + " file doesnot exist");
            return null;
        }
        if (!file.isDirectory())
        {
            log.error(inputDir + " is not a directory");
            return null;
        }

        if (file.isDirectory())
        {
            getFolderFolderList(file);
        }

        return file.list();
    }

    public String[] getFolderFolderList(File directory)
    {

        File[] files = directory.listFiles();
        for (File file : files)
        {
            if (file.isDirectory())
            {
                // recursively traverse directory
                getFolderFolderList(file);
            } else
            {
                // add to list ?
            }
        }
        return list; // ?

    }

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35013232
Sorry, didn't understand you, is it a question?
0
 

Author Comment

by:AndyC1000
ID: 35013367
Sorry I wrote it quickly.

My main questions are:

1.  In the traverse methodhow to save the actual files in a list. that will:

2.  work in the processFiles method,
File file = new File(list[i]); 

Open in new window

since there is no directory path.

Thanks for your help!
 

0
 
LVL 47

Accepted Solution

by:
for_yan earned 250 total points
ID: 35013410

I believe you may want something like below.
First you create the list of full filenames and then do with
your files waht you want.

it is easier to start with ArrayList, not witn array,
as you will not know upfront how many files
you expect to have.

Let me know if you have any questions

public class ListFilesAndFolders {

ArrayList longFileNames;

public ListFilesAndFolders(){

longFileNames = new ArrayList();
traverse("C:\\input");
//at this point you have ArrayList with full names of all files

String [] fileList = new String[longFileNames.size()];

for(int j=0; j<longFileNames.size();j++){
fileList[j] = (String)longFileNames.get(j);

processFiles(fileList);


}

public static void traverse(File directory)
{
   // Get all files in directory

   File[] files = directory.listFiles();
   for (File file : files)
   {
      if (file.isDirectory())
      {
         // Its a directory so (recursively) traverse it

         traverse(file);
      }
      else
      {
 longFileNames.add(file.getAbsolutePath());

         // its a file, do any processing you require here
      }
   }
}
}

private void processFiles(String [] listOfFullFilenames){
// your code where you do something with each file one by one
}

public static void main(String [] args){
new ListFilesAnd Folders();
}

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
firstswap challenge 20 67
Java passing arguments (type error) 2 48
why cannot we forward request once the response is committed 2 33
expectj telnet failing 5 26
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now