Count files in Directory and the number of files in each sub directory

Hello,
I trying write a method which will start at a root of a file and count all the files in that directory. Then count all the files in each sub directory.
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class RunScan {
     * @param args
     public static void main(String[] args) {
          // TODO Auto-generated method stub
          File file = new File("/home/robert/count");
          File[] files = file.listFiles();
          traverse(files);
          printfiles();
     private static int totalNumFiles = 0;
     private static int totalNumDir = 0;
     private static int filePerDir = 0;
     private static int subDir = 0;
     private static void traverse(File[] files) {
for(int i = 0; i < files.length; i++) {
if(files.isDirectory()) {
     totalNumDir++;
     printDir(files[i].toString());
     traverse(files[i].listFiles());
totalNumFiles++;
filePerDir++;
     private static void printfiles(){
          System.out.println("total files "+ (totalNumFiles));
     System.out.println("totls sub dir "+ totalNumDir);
     private static void printDir(String dirName){
          System.out.println("Total Files in "+dirName+" "+filePerDir);
          filePerDir = 0;

Hint: Google "visitor pattern." This gives clues how to build a re-usable solution that can you use for future traversals that do things other than just file counts. Here's a teaser of an simple interface:
public interface TreeVisitor {
* Processes a single file or directory. <em>Tip:</em> If you want to track the number of
* items processed, this function is the best place to update a counter.
* Implementors of this method should not throw checked exceptions.
* @param item The file or directory process.
* @param depth Number of levels below top of traversal tree (0 = top of tree).
public void visit(File item, int depth);
}

Similar Messages

  • I have been working on the same numbers file for the past few weeks.  The last time I opened it was 1 week ago.  Today when I tried to open it I am unable and getting a message that the file is invalid and the index.xml file is missing.

    I have been working on the same numbers file for the past few weeks.  The last time I opened it was 1 week ago.  Today when I tried to open it I am unable and getting a message that the file is invalid and the index.xml file is missing. 

    Hi Tracie,
    I upgraded to Maverick OS X 10.9.5, numbers spreadsheet is saved. Upon re-opening, it appears to be frozen, a warning "file is invalid as index.xml file is missing". I checked, and the file is not "locked". This appears to occur only with using the new numbers app. When I open previous spreadsheets from old iWorks, no such problem occurs.
    How did you resolve your problem?
    Would appreciate any help here.
    Thanks,
    Deehay

  • Count the number of lines in  each file in a directory

    Hello,
    I would like to count the number of lines for each file in my directory and subdirectories.
    I wonder how can I count the lines of the specified files?
    Here is the program which is listed the files in the specified directory:
                        String path = "C:/User/Studies/Pracices/src/Pract1";
           String files;
           File folder = new File(path);
           File[] listOfFiles = folder.listFiles();
           for (int i = 0; i < listOfFiles.length; i++)
            if (listOfFiles.isFile())
         files = listOfFiles[i].getName();
         System.out.println(files);

    Ok so one more question.
    Actually my path is pointing to one Directory and like here I can just read from one file that the name of the file should be specified in the path is it possible to help me in that part?
    File f = new File("C:/User/Studies/Practices/src/Pract1/");
    FileReader fr = new FileReader(f);
          BufferedReader br = new BufferedReader(fr);
          String str = br.readLine();
              LineNumberReader ln = new LineNumberReader(br);
              int count = 0;
              while (ln.readLine()!=null)
                  count++;
              System.out.println("no. of lines in the file = " + count);

  • Programatically count the number of files in a folder

    Hi Folks
    I need to programatically count the number of files in a given folder and return the value to a Program Unit to be included in further processing.
    Can anyone point me in the right direction. I have looked at UTL_FILE but this does not offer what I want.
    Does anyone know of an obscure package in Oracle that I could use?
    I'm using 9i in a W2K environment.
    Many thanks
    Simon Gadd

    Hi,
    following a java based solution i found somewhere on Tom Kyte's AskTom forum.
    GRANT JAVAUSERPRIV to TESTUSER;
    dbms_java.grant_permission( 'TESTUSER', 'SYS:java.io.FilePermission', 'c:\', 'read' );
    create global temporary table DIR_LIST
    ( filename varchar2(255) )
    on commit delete rows
    create or replace and compile java source named "DirList"
    as
      import java.io.*;
      import java.sql.*;
      public class DirList
        public static void getList(String directory)
                           throws SQLException
          File path = new File( directory );
          String[] list = path.list();
          String element;
          for(int i = 0; i < list.length; i++)
              element = list;
    #sql { INSERT INTO DIR_LIST (FILENAME)
    VALUES (:element) };
    create or replace procedure get_dir_list( p_directory in varchar2 )
    as language java
    name 'DirList.getList( java.lang.String )';
    exec get_dir_list( 'c:\temp' );
    select count(*) from dir_list;

  • How to find the number of files in an oracle directory through a storedproc

    hi
    i have an oracle directory or a directory in an ftp server
    is there any way.......through which..
    i can know the number of files in the directory ...?
    and whats the metadatacolumn that will indicate the name of the file?
    and is it possible to loop through each of the entries within oracle
    regards
    raj

    ops$tkyte@8i> GRANT JAVAUSERPRIV to ops$tkyte
      2  /
    Grant succeeded.
    That grant must be given to the owner of the procedure..  Allows them to read
    directories.
    ops$tkyte@8i> create global temporary table DIR_LIST
      2  ( filename varchar2(255) )
      3  on commit delete rows
      4  /
    Table created.
    ops$tkyte@8i> create or replace
      2     and compile java source named "DirList"
      3  as
      4  import java.io.*;
      5  import java.sql.*;
      6 
      7  public class DirList
      8  {
      9  public static void getList(String directory)
    10                     throws SQLException
    11  {
    12      File path = new File( directory );
    13      String[] list = path.list();
    14      String element;
    15 
    16      for(int i = 0; i < list.length; i++)
    17      {
    18          element = list;
    19 #sql { INSERT INTO DIR_LIST (FILENAME)
    20 VALUES (:element) };
    21 }
    22 }
    23
    24 }
    25 /
    Java created.
    ops$tkyte@8i>
    ops$tkyte@8i> create or replace
    2 procedure get_dir_list( p_directory in varchar2 )
    3 as language java
    4 name 'DirList.getList( java.lang.String )';
    5 /
    Procedure created.
    ops$tkyte@8i>
    ops$tkyte@8i> exec get_dir_list( '/tmp' );
    PL/SQL procedure successfully completed.
    ops$tkyte@8i> select * from dir_list where rownum < 5;
    FILENAME
    data.dat
    .rpc_door
    .pcmcia
    ps_data
    http://asktom.oracle.com/pls/asktom/f?p=100:11:4403621974400865::::P11_QUESTION_ID:439619916584
    Edited by: Salim Chelabi on 2009-04-21 10:37

  • Finder issues and Get Info refusing to show the number of files on items on the main hard drive.

    I am having finder issues. Mostly on the main hard drive. It takes ages to find things and I get the spinning wheel every time I open a folder.
    So I moved all of my files to a external drive.  When I had finished transfering I hit get info on the files on the external drive and on the same folder on the main drive.  To ensure that it has copied over all the files.  Because it was acting up and not copying all the files.
    Get Info refuses to show the number of files within the folders on the main hard drive. It hasppily tells me everything on any of the external drives.
    I have reset, the imac.  I have re indexed 3 times.  I have deleted the finder plist files.  I have reset finder using terminal commands. I have moved nearly everything off the main hard drive. But nothing is working.
    Can anyone offer any suggestions as to what could be causing my finder and get info issues.
    Any help wpuld be appreciated.
    Running Mountain Lion on a late 2009 Imac

    Some of your user files (not system files) have incorrect permissions or are locked. This procedure will unlock those files and reset their ownership, permissions, and access controls to the default. If you've intentionally set special values for those attributes, they will be reverted. In that case, either stop here, or be prepared to recreate the settings if necessary. Do so only after verifying that those settings didn't cause the problem. If none of this is meaningful to you, you don't need to worry about it, but you do need to follow the instructions below.
    Back up all data.
    Step 1
    If you have more than one user, and the one in question is not an administrator, then go to Step 2.
    Enter the following command in the Terminal window in the same way as before (triple-click, copy, and paste):
    sudo find ~ $TMPDIR.. -exec chflags nouchg,nouappnd,noschg,nosappnd {} + -exec chown $UID {} + -exec chmod +rw {} + -exec chmod -N {} + -type d -exec chmod +x {} + 2>&-
    This time you'll be prompted for your login password, which won't be displayed when you type it. Type carefully and then press return. You may get a one-time warning to be careful. If you don’t have a login password, you’ll need to set one before you can run the command. If you see a message that your username "is not in the sudoers file," then you're not logged in as an administrator.
    The command may take several minutes to run, depending on how many files you have. Wait for a new line ending in a dollar sign ($) to appear, then quit Terminal.
    Step 2 (optional)
    Take this step only if you have trouble with Step 1, if you prefer not to take it, or if it doesn't solve the problem.
    Start up in Recovery mode. When the OS X Utilities screen appears, select
              Utilities ▹ Terminal
    from the menu bar. A Terminal window will open. In that window, type this:
    res
    Press the tab key. The partial command you typed will automatically be completed to this:
    resetpassword
    Press return. A Reset Password window will open. You’re not going to reset a password.
    Select your startup volume ("Macintosh HD," unless you gave it a different name) if not already selected.
    Select your username from the menu labeled Select the user account if not already selected.
    Under Reset Home Directory Permissions and ACLs, click the Reset button
    Select
               ▹ Restart
    from the menu bar.

  • [Win VC++ 6.0 ]How to get the number of files count in a folder using VC++ 6.0?

    Hi all,
    Can any one tell how to get the number of files(.EPS) count inside a folder when the folder path is specified in VC++ 6.0?
    Thanks in Advance.
    Regards
    myriaz

    I'm a little confused by the question, but it sounds like you're asking how to count the number of files with a particular extension in a given directory? That's not really an AI SDK question, but it's a fairly easy one to find if you google it. If you're trying to use Illustrator to do it, AI doesn't have a general purpose file API. It has a few functions to do some things that Illustrator needs, but I don't think enumerating directories is one of them.

  • How to list the contents of an OSX directory, and output to text file?

    hello there any hints with any known program that does following
    I have recorded my music directory to DVD and now i would like to make an .txt file what the dvd contains...cos its way of hand to write all 100xx files by hand...
    How to list the contents of an OSX directory, and output to text file?
    any prog that does that? any hints?
    best regards

    This script makes a hierarchical file listing all files in a folder and subfolder:
    Click here to launch Script Editor.
    choose folder with prompt "Choose a folder to process..." returning theFolder
    set theName to name of (info for theFolder)
    set thepath to quoted form of POSIX path of theFolder
    set currentIndex to theFolder as string
    do shell script "ls -R " & thepath returning theDir
    set theDirList to every paragraph of theDir
    set newList to {"Contents of folder \"" & theName & "\"" & return & thepath & return & return}
    set theFilePrefix to ""
    repeat with i from 1 to count of theDirList
    set theLine to item i of theDirList
    set my text item delimiters to "/"
    set theMarker to count of text items of thepath
    set theCount to count of text items of theLine
    set currentFolder to text item -1 of theLine
    set theFolderPrefix to ""
    if theCount is greater than theMarker then
    set theNestIndex to theCount - theMarker
    set theTally to -1
    set theFilePrefix to ""
    set theSuffix to ""
    repeat theNestIndex times
    set theFolderPrefix to theFolderPrefix & tab
    set theFilePrefix to theFilePrefix & tab
    if theTally is -1 then
    set theSuffix to text item theTally of theLine & theSuffix
    else
    set theSuffix to text item theTally of theLine & ":" & theSuffix
    end if
    set currentIndex to "" & theFolder & theSuffix
    set theTally to theTally - 1
    end repeat
    end if
    set my text item delimiters to ""
    if theLine is not "" then
    if word 1 of theLine is "Volumes" then
    set end of newList to theFolderPrefix & "Folder: > " & currentFolder & return
    else
    try
    if not folder of (info for alias (currentIndex & theLine & ":")) then
    set end of newList to theFilePrefix & tab & tab & tab & "> " & theLine & return
    end if
    end try
    end if
    end if
    end repeat
    open for access file ((path to desktop as string) & "Contents of folder- " & theName & ".txt") ¬
    with write permission returning theFile
    write (newList as string) to theFile
    close access theFile

  • After I run a query can I get it to return the number of files matched and each individual file name?

    After I run a query can I get it to return the number of files matched and each individual file name?  I am trying to do a data mining routine and this would be helpful. 
    BBANACKI

    Hi bbanacki,
    Please have a look at the following code:
    Define your queries and then:
    oAdvancedQuery.ReturnType=eSearchFile
    oMyDataFinder.Results.MaxCount = iMaxNumberOfReturndElements
    Call oMyDataFinder.Search(oAdvancedQuery)
    Set oMyResults  = oMyDataFinder.Results
    If oMyResults.IsIncomplete Then
      msgbox "The first " & str(oMyResults.Count) & " files found"
    Else
      msgbox str(oMyResults.Count) & "  files found"
    End If
    for iLoop = 1 to oMyResults.Count
      Cell.Text = oMyResults(iLoop).Properties("Name").Value
      Cell.Text = oMyResults(iLoop).Properties("fullpath").Value
    next
    Greetings
    Walter

  • Why does OS X Finder recognize a folder as a file when it counts the number of files?

    When I select a folder in Finder and click cmd+i(or cmd+option+i), it shows the number of files in the folder. However, that number is weird for me, because they count a folder itself as a file. For example, when I have a single file in my Download folder and I clicked cmd+i on Download folder, then the number of files in a inspection window is 2, not 1. It is because that number includes not only the file inside the folder, but also the folder itself. (Check the below image)
    This is not a big problem if there is no hierarchical structure in my folder. But, if I have thousands of files and folders inside, it is really hard to figure out how many files(not folders) are inside. I cannot understand why Mac OS X counts a folder as a file. In fact, a folder is not an actual file, just a container.
    So, is there any philosophy to do like this? Or is there any way to count only the number of actual files?

    Sorry byron1st
    there is no way to count only files in a folder.
    Finder will count everything inside, folders and files.
    Information about a folder will count the same.
    If there are no subsubfolders in one folder, maybe a little trick can help:
    Select list view for the open folder, close all subfolders.
    Type command+# to see the footer of the window, that counts (hopefully) only the closed subfolders (content) in the open folder.
    Remember the amount.
    Hold option and click on one triangle in front of one subfolder. All subfolders will be opened!
    The difference between amount a and amount b is the number of files (and subsubfolders, if unfortunately inside…).

  • What is the difference between partition-count and the number of caches?

    What is the difference between partition-count and the number of caches in Coherence? Are they same?

    Those are totally orthogonal concepts.
    For more, look at this thread where I answered your other related questions and explain this, too:
    Where can I find the accurate definitions of these terms?
    Best regards,
    Robert

  • Is there a connection between the performance and the number of photos?

    Is there a connection between the performance of LR 4 (LR 5) and the number of photos in the catalog? Will it slow down LR with a directory of more than 40,000 images (Win7, 4 Gb RAM)?

    I use lots of smart and dumb collections, lots of keywords too, also on Win7/64 though with 12Gb of Ram.
    Have you read through Optimizing performance, especially running a File > Optimize. Also Performance hints is more handy for troubleshooting.
    John

  • How can I export the number of pixels of each layer into an excel file?

    I would like to export the number of pixels that each layer of an image contains into excel. How can I do this?
    Secondly, as I need to do this with several images, is there any way to name the layers so that all layers with let's say for example the name "yellow" appear in the same column in excel?
    Some background information on why I need to do this... I would like to know how many percent of an image are yellow and have therefore created  layers of one image for each color it contains.
    Thanks for your help!!!

    Maybe my question was a bit unclear. I do not want to find out the number of pixels of a color in a layer but the number of pixels of the complete layer.
    What color these layers are is a different question. I am using images with a very limited range of colors (sort of like the image above but with about 10 colors). I have seperated these colors into layers and now need to count the pixels of each layer and export them.
    You can record number of pixels/layer  into the Measurement Log, then export data to Excel. But I'm not sure how to automate that without scripting.
    Does anyone know how to do this?
    For normal artLayers it is somewhat easy to get the number of pixels in the layer. But that is just how many pixels are in the layer.
    But that is exactly what I need to know, how many pixels are in the layer. I know how to find this out by looking at the histogram of the selection. But I want to export this information of all layers at once into an excel or text file. Any ideas on how to automate this with or without scripting?
    |

  • Limit on the number of file names retrieved using FM 'RZL_READ_DIR_LOCAL'

    Hi All,
    I am using FM 'RZL_READ_DIR_LOCAL' , to retrieve file names from a specified directory.
    When executed, i am getting 10,000 records(file names) only against lakhs of files present in the directory.
    I would like to know if there is any limitation on the number of file names retrieved using that FM and how to over come it.
    Also please let me know if the FM 'EPS2_GET_DIRECTORY_LISTING' also has any such limitations.
    Thanks in advance,
    Sreeni Vallem

    I did not know about this limitation of number of files returned. You can give a try to the external command way of doing it in your development system.  Well, creating 10001 files in development is a boring job . You can write a sample program as Rob has mentioned in this thread and copy files to a specific directory ABAP: Copy files from one R3 directory to another. This doesn't disturb the existing program written.
    Mean while let's wait for expert's reply.
    Kesav

  • Add Folder - is there a limit to the number of files you can add in one go?

    I have a fairly large collection (60GB+) of 192kbps mp3 files which are stored under My Music in a folder structure of Artists / Album, e.g. "My Music \ ACDC \ Back in Black\ Hells Bells.mp3"
    I recently bought an ipod and having installed itunes I wanted to add all my music. I figured out that the way to do this is to go File / Add Folder and select the "My Music" folder.
    However, itunes starts adding the mp3s and stops at the Bruce Springsteen folder. At this point the itunes library can see all the "A" folders and the "Bs" up to and including Bruce Springsteen. If I try the process again nothing happens.
    However, if I then try to add a specific folder e.g. "My Music \ Charlatans" it works.
    This suggests to me that the Add Folder option has a limit to the number of files it can process.
    Any thoughts on this would be appreciated as I'm not looking forward to manually adding a hundred or so folders.
      Windows XP  

    Well the part about putting songs in the "iTUnes Music" folder I only brought up because it seemed you liked things very organized. You could use iTunes to so all the organizeing. Plus once you add something to the iTUnes library, if you change ANYTHING about it in windows explorer, like its name, change the name of the folder its in or move it to another folder, iTUnes "Looses Track" of it. Its not like other programs that "Watch" files and folders for changes outside its "iTUnes Music" folder
    But to have iTUnes auto search, you have to delete a hidden pref file. After doing this, when you open iTUnes again it will throw up a setup wizard, just like its the first time ever installing it. Its in this wizard where you get your ONLY chance to have iTUnes auto search and add files from the system. Just goto the link below and follow Scott P's steps
    http://discussions.apple.com/message.jspa?messageID=607357
    Also since your new to the ipod, you my want to check out the "iPod 101" section so you can learn the ropes of everything
    http://www.apple.com/support/ipod101/

Maybe you are looking for

  • Problem showing DATE data and slow history in version 3.0.02

    Hello: I have 2 problems with this new version: When I press "F8" the history works veryyyyyyyy slowwwwwww... ¿? Second problem: I have defined these preferences... NLS Date format: DD/MM/YYYY HH24:MI:SSXFF Hour Register format: DD/MM/YYYY HH24:MI:SS

  • Material Subject to Batch Management

    Dear All,         In production client, the user by mistake has put the tick for batch management while creating material.Actually, the material was not subject to batch management. Later, PO was created. At the time of GR against this PO, the store

  • DPM 2012 R2 console crash after RU5 install

    Hello all, recently I update my DPM to RU5 and since then then I click on management tab the console crash. I tried Islam's solution but it is not working for me. In the event I get this: The description for Event ID 999 from source MSDPM cannot be f

  • Upgrade Oracle 9.2.0.5 to Oracle 11g

    Hi, Any one done a upgrade of oracle 9.2.0.5 to 11g R2 ? I have two databases : 1. 9.2.0.5 in RAC mode 2. 9.2.0.7 Any idea how long would if take to upgrade the RAC instance ? I also need to know if PRO*C programs can be directly upgraded to the 11gR

  • Smart form for maint . order

    hi i have to make a smart form for maintenance order. i would be required for following fields- mant. order no, equipment no, maint date, task performed, purchase prder no, vendor no, spare to be used, reservation no. kindly give the process for the