Solved

How to read files in nested directories in Java

Posted on 2011-03-01
7
369 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jar file executable 12 58
servlet example 17 51
Delete Android all or certain applications data programmatically 9 70
Java syntax, or is it Selenium 6 30
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 will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

839 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