Directory Walker : Directory « File Input Output « Java






Directory Walker

      


/**
 * Title:        NoUnit - Identify Classes that are not being unit Tested
 *
 * Copyright (C) 2001  Paul Browne , FirstPartners.net
 *
 *
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * @author Paul Browne
 * @version 0.6
 */

import java.io.*;
import java.util.*;


/**
 * 'Walks' the directory structure and returns files found (including those in sub folders)
 */
public class DirectoryWalker {

    /**
     * Get all the files in the starting directory (and sub dirs)
     * No filter
     * @param startingDirectory
     * @return filesFound (as HashSet)
     * @exception java.io.IOException
     */
    public static HashSet getFiles(String startingDirectory)
        throws java.io.IOException {
        
       return getFiles(startingDirectory,null);
    }
  
   /**
     * Get all the files in the starting directory (but NOT sub dirs)
     * returns only files ending this the filename
     * @param startingDirectory
     * @return filesFound (as HashSet)
     * @exception java.io.IOException
     */
    public static HashSet getFiles(String startingDirectory,String endFileName)
        throws java.io.IOException{
        
        //Local Variables
        String tmpFullFile;
        File startDir = new File(startingDirectory);
        File tmpFile;
        String[] thisDirContents;
        HashSet filesFound = new HashSet();
        
        //Check that this is a valid directory
        if (!startDir.isDirectory()) {
            throw new java.io.IOException(startingDirectory+" was not a valid directory");
        }
        
        //Get the contents of the current directory
        thisDirContents = startDir.list();
        
            if (thisDirContents!=null) {
            //Now loop through , apply filter , or adding them to list of sub dirs
            for (int a=0; a<thisDirContents.length;a++) {

              //Get Handle to (full) file (inc path)  
              tmpFullFile=FileUtil.combineFileAndDirectory(thisDirContents[a], 
                                                                    startingDirectory);

              tmpFile = new File(tmpFullFile);

                //Add to Output if file
                if (tmpFile.isFile()) {
                    //Add if file 
                    if ((endFileName==null)||
                        (tmpFullFile.endsWith(endFileName))){
                              filesFound.add(tmpFullFile);
                    }
                }
            }
         }
            
        return filesFound;
        
    }
    
    /**
     * Get all the Directories in the starting directory (and sub dirs)
     * returns only files ending this the filename
     * @param startingDirectory
     * @return filesFound (as HashSet)
     * @exception java.io.IOException
     */
    public static HashSet getDirs(String startingDirectory)
        throws java.io.IOException{
        
        //Local Variables
        String tmpFullFile;
        String tmpSubDir;
        File startDir = new File(startingDirectory);
        File tmpFile;
        String[] thisDirContents;
        HashSet dirsFound = new HashSet();
        HashSet subDirFilesFound;
        
        //Check that this is a valid directory
        if (!startDir.isDirectory()) {
            throw new java.io.IOException(startingDirectory+" was not a valid directory");
        }
        
        //Add the current directory to the output list
        dirsFound.add(startingDirectory);
        
        //Get the contents of the current directory
        thisDirContents = startDir.list();
        
            if (thisDirContents!=null) {
            //Now loop through , apply filter , or adding them to list of sub dirs
            for (int a=0; a<thisDirContents.length;a++) {

              //Get Handle to (full) file (inc path)  
              tmpFullFile=FileUtil.combineFileAndDirectory(thisDirContents[a], 
                                                                    startingDirectory);

              tmpFile = new File(tmpFullFile);
                
              //We're only interested in directories
                if (tmpFile.isDirectory()) {
                    
                    //Add this to the directory list
                    dirsFound.add(tmpFullFile);
                    
                    //Now Do Recursive Call (to this method)if Directory
                    tmpSubDir = FileUtil.combineFileAndDirectory(thisDirContents[a], 
                                                                    startingDirectory);
                    subDirFilesFound = DirectoryWalker.getDirs(tmpSubDir);
                    dirsFound.addAll(subDirFilesFound);
                }   

            }
         }
            
        return dirsFound;
        
    }

}


/**
 * Title:        NoUnit - Identify Classes that are not being unit Tested
 *
 * Copyright (C) 2001  Paul Browne , FirstPartners.net
 *
 *
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * @author Paul Browne
 * @version 0.6
 */


/**
 * Class to manage files within a directory structure<BR>
 */
 class FileUtil {

 /**
   * Combines file and directory , using path delimeters
   * @param fileName
   * @param filePath
   * @return combinedPath
   */
  public static String combineFileAndDirectory (String fileName , String filePath) {

    String combinedPath = null;

    //Checking incoming values
      if ((fileName==null)||(filePath==null)) {
        return null;
      }

      if ((fileName.equals(""))||(filePath.equals(""))) {
        return null;
      }

    //Add character to end of Directory if required
    if ((filePath.endsWith("\\")||(filePath.endsWith("/")))) {
      //nothing
    } else {
      //add character
      filePath = filePath + String.valueOf(File.separatorChar);
    }

    //Add two together
    combinedPath = filePath+fileName;

    return combinedPath;

  }
   
}

   
    
    
    
    
    
  








Related examples in the same category

1.Create directory
2.Create directory along with required nonexistent parent directories
3.Create directory tree (nested/cascade folders)
4.Create a directories recursively
5.Copying a Directory: Copies files under srcDir to dstDir, if dstDir does not exist, it will be created.
6.Delete a non-empty directory: Deletes all files and subdirectories under dir.
7.Listing the Files or Subdirectories in a Directory
8.Listing the File System Roots
9.The Directory Listing ApplicationThe Directory Listing Application
10.use list( ) to examine the contents of a directory:
11.Reading and Printing a Directory HierarchyReading and Printing a Directory Hierarchy
12.Display a file system in a JTree viewDisplay a file system in a JTree view
13.File Tree DemoFile Tree Demo
14.File Table HTMLFile Table HTML
15.A standalone program that deletes a specified file or directory
16.Get Last modification time of a file or directory
17.Set last modified time of a file or directory
18.List contents of a directory
19.Determine if file or directory exists
20.Determine if File or Directory is hidden
21.Check if a directory is not empty
22.Get name of parent directory
23.Get name of specified file or directory
24.Get current directory
25.Mark file or directory Read Only
26.Rename file or directory
27.Traversing all files and directories under dir
28.Traversing only directories under dir
29.Traversing only files under dir
30.Creates and displays a window containing a list of files and sub-directories in a specified directory
31.Calculate directory size
32.Delete directory recursively
33.Determining If Two Filename Paths Refer to the Same File
34.Recursive directory deletion
35.Recursivly delete directory
36.Searches through the directory tree
37.Starts at the directory given and tests to see whether it is empty
38.Utility methods for handling files and directories
39.Creates a new and empty directory in the default temp directory using the given prefix.
40.Count files in a directory (including files in all subdirectories)
41.Create a unique directory within a directory 'root'
42.Creates a new empty temporary directory.
43.Get Files Recurse
44.Recursively search a directory tree
45.Find directoriesFind directories