Solved

How to read files in nested directories in Java

Posted on 2011-03-01
7
362 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

758 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

20 Experts available now in Live!

Get 1:1 Help Now