Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How to read files in nested directories in Java

Posted on 2011-03-01
7
Medium Priority
?
394 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

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 1000 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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

610 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