Solved

How to read files in nested directories in Java

Posted on 2011-03-01
7
367 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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Image decoding from Camera 3 85
JavaScript/Java - Changing an image background color 4 65
couple of eclipse 5 35
tomcat not starting 6 45
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

815 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

11 Experts available now in Live!

Get 1:1 Help Now