How to iterate contents of a directory?

How do I iterate all the files and subdirectories of a directory, whose depth I don't know?

A rough idea, you could do it recursively, but this is easier:
import java.util.Stack;
import java.util.Arrays;
public
class Pops
  public
  static
  void main(String[] args)
    File file = new File(args[0]);
    Stack stack = new Stack();
    Stack files = new Stack();
    stack.add(file);
    stack.addAll(Arrays.asList(file.listFiles()));
    while (!stack.empty())
      file = (File)stack.pop();
      if (file.isDirectory()) { stack.addAll(Arrays.asList(file.listFiles())); }      files.push(file);
    while (!files.empty())
      System.out.println(files.pop());

Similar Messages

  • How to retreive contents of a directory

    I'm writing a java web application.
    In one of my classes (standard class) I want to see what files are located in a specific directory. I just want to retreive all the filenames that are in that specific directory.
    Could anyone give me some advice.
    Thanks in advance
    Jeroen

    This should help:
    import java.io.File;
    String directoty =  "c:\\temp";
    File f = new File( directoty );
    if( ! f.isDirectory() )
      throw new IllegalArgumentException( "Path '" + directoty + "' is not a Directory" );
    File[] dirContents =  f.listFiles();
    System.out.println( "Files in Directory '" + directoty + "':\n" );
    for( int i = 0; i < dirContents.length; i++ )
      System.out.println( "\t" + dirContents.getName() );
    Good Luck!

  • How to see the contents of a directory?

    ok, here is my problem. I need to see the contents of a directory (ie. like doing a dir in DOS or ls in Linux) and then process each of the files in the directory.
    Is there a way in java to see the contents of a directory? Please help...

    hi,
    well you can see the contents of a directory, a directory in turn could have files and subdirectories, so you could use the following snippet of code.
    import java.io.File;
    import java.io.IOException;
    public class FileBrowser
         private File mFile;
         public void listDirectory(String fileName)
              mFile = new File(fileName);
              if (mFile.exists()) //check if File or Directory with given name exists
                   if (mFile.isDirectory())
                        File mTempFile[] = mFile.listFiles();
                        if (mTempFile.length > 0)
                             for (int i=0; i < mTempFile.length; i++)
                                  listDirectory(mTempFile.getAbsolutePath()); //recursive call
                   else if (mFile.isFile())
                        printFilePath(mFile);
              else
                   throw new IllegalArgumentException("File or Directory does not exist");
         public void printFilePath(File file)
              System.out.println("File path :" + file.getAbsolutePath());
         public static void main(String args[])
              try
                   FileBrowser fb = new FileBrowser();
                   fb.listDirectory("c://temp//");
              catch(IllegalArgumentException ex)
    the above code snippet first figures out if a File object is representing a File or a Directory, if it represents a File it just call a method which prints out the Absolute path of the file which contains the file name also, else if it is a directory it just recursively scans through all sub-directories and files within the directory, also if the String arguement passed to listDirectory is incorrect, it throws a IllegalArguementException, hope this was useful.
    Cheerz

  • Read content of a directory

    Hi all,
    I'm searching for a way on how to read the content of a directory on a local machine..
    This has to be done in background.
    Does someone has an idea ?
    tia,
    Björn

    Hi Bjorn,
    try to search on and use the open dataset - read dataset - close dataset.
    Hope this helps.
    Regards,
    Vitz

  • How to Keep Content Types Current with Updated Data

    Let’s say that I have four content types—content type 1, content type 2, content type 3, and content type 4—all based on the same list, say list A.
    Each content type has its own workflow.
    When the workflow for content type 1 is completed, the data is saved to an individual item, say item Z, in a separate list, list B.
    When the workflow for content type 2 is completed, the data is saved to the same item (item Z) in list B. The reason that there are two lists is that the creation of content types causes new items to be created, but the each
    new item must reference data from the previous item. That means that data has to be copied from the first item to the second item. But what happens to the data in the second item when data from the first item is changed? The solution is to have a single item
    in another list to which all content types write their data.
    What I need to know is how can all the content types retrieve data from list B when those content types are based on list A? For example, let's say that content type 3 uses data originally input through content type 1. As the
    user inputs and saves data through content type 3 he sees data that had been originally input through content type 1. Another user then accesses content type 1 to update and save data through it. When content type 3 is opened again that user will not see the
    updated data entered through content type 1 because it is tied to a different item. The solution seems to be for all content types to save their data to the same item in another list. But then how can those content types be designed so that when they open
    they show updated data from List B when those content types are based on List A?
    Other applications have the notion of a folder containing all the up-to-date data fields. Another way to look at this problem is to state what SharePoint 2007 does to mimic the notion of a folder.

    Thanks for responding, but I don't think that the solution provided solves my problem. What you described will keep the item in List B in sync with the changes made to List A. However, the content types from List A will not be in sync when they are opened
    from List A. Say content type 1 makes changes to various fields. When content type 3 opens it displays some of the fields that content type 1 changed; however, content type 3 and content type 1 by definition display different items--and those items are not
    in sync. Either I have to copy the updated item from List B back to the related items in List A or there has to be another solution.
    Is it possible to have a workflow update all the items in a list based on a key field whenever changes are made to that item. Say content types 1, 2, 3, and 4 already exist and each refers to a different item in List A, but they are "tied" together
    by a key field. When content type 1 is reopened and changes are made, is it possible to iterate over the items in a list to find other items whose key field matches the key field from content type 1? If so, then when matching items are found the fields in
    them can be updated by the same changes made to content type 1.
    If this latter scenario is possible, how is that iteration set up in a SharePoint 2007 workflow? Thanks again.

  • Finder (Snow Leopard 10.6.8) taking long time to load contents of any directory. Please help?

    In my macbook pro 5,2 snow leopard (10.6.8), Finder taking long time to load contents of any directory. Please help?
    I have already tried to spotlight re-indexing but it did not help. I am hardly able to work on it, almost for each directory I browse its keeps on spinning for 1min.

    Download iTunes from Apple's web site and install it.  Don't use Software Update.

  • How can I convert the volume directory into a single file installer?

    How can I convert the volume directory into a single file installer? I would like to hide all the miscillaneous files that I don't care for and be able to have the installer double click a single file and have it automatically install.

    On the second prompt screen when prompted 'What kind of self-extracting Zip file file do you want to make?'
    Are you choosing the second option (self-extracting Zip file for software installation)?
    I have a word file that I created to help me remember - is there anyway to email it to you?

  • I've had a hard drive crash and put in a new one.  However iTunes has or list all of them from my old drive.  How do we re-set the directory

    I've had a hard drive crash and put in a new one.  However iTunes has or list all of them from my old drive.  How do we re-set the directory?

    You can re-download the software from Download CS5.5 products
    Install and enter your serial number when prompted.
    Find your serial number quickly

  • How to find content of a constraint etc.

    Hi,
    select constraint_name
    from user_constraints
    where table_name = 'EMP';
    shows to two constraints for the given table of EMP. Now, how to find CONTENT of each of these two constraints?
    Secondly, how to find if a particular column is nullable (programmatically, not from DBA tool set)? e.g. EMP.deptno
    Thirdly, why did I get the err msg of "inserted value too large for column"
    when executing the following command for data insertion to EMP as user, scott
    create SEQUENCE emp_sequence
    start with 8000 increment by 10;
    insert into EMP values (emp_sequence.NEXTVAL,'JOE','Researcher',null,null,null,null,null);
    Thanks a bunch.

    Thirdly, why did I get the err msg of "inserted value too large for column"Er, do the math...
    SQL> conn scott/tiger
    Connected.
    SQL> desc emp
    Name                                      Null?    Type
    EMPNO                                     NOT NULL NUMBER(4)
    ENAME                                              VARCHAR2(10)
    JOB                                                VARCHAR2(9)
    MGR                                                NUMBER(4)
    HIREDATE                                           DATE
    SAL                                                NUMBER(7,2)
    COMM                                               NUMBER(7,2)
    DEPTNO                                             NUMBER(2)
    SQL> select length('researcher') from dual
      2  /
    LENGTH('RESEARCHER')
                      10
    SQL>
    Secondly, how to find if a particular column is nullable (programmatically, not from DBA tool set)Don't like the sound of this, smells of dynamic coding. Anybody who can't figure out why they can't create an EMP record for a researcher probably ought not to be tangling with dynamic SQL just yet.
    Now, how to find CONTENT of each of these two constraints?The CONSTRAINT_TYPE tells you the sort of constraint: P=PRIMARY KEY, U=UNIQUE, R=FOREIGN KEY and C=CHECK. Only Check constraints have any content as such and you'll find that in the SEARCH_CONDITION. Note that this is a LONG column, so you may need need to SET LONG 5000 to see it in SQL*Plus.
    Cheers, APC
    P.S. In future please refrain from bundling unrelated questions into a single post. There is no charge for posting and it avoids the threads getting long and hard to follow.

  • How to install content server

    Hi all,
    I am new to DMS.How to install content server? and What is the difference between Content server and Kpro server?
    Thanks and Regards,
    Vairavan

    Hi Vairavan
    try SAP Service Marketplace at service.sap.com/contentserver and
    try the Installation Guides at service.sap.com/instguides -> SAP NetWeaver -> SAP NetWeaver 7.0 (2004s) -> Installation -> Installation u2013 Standaline Engines.
    regards, Andreas R

  • How to import your MS Active Directory users in an Oracle table

    Hello,
    I first tried to get a Heterogenous Connection to my MS Active Directory to get information on my Active Directory users.
    This doesn't work so I used an alternative solution:
    How to import your MS Active Directory users in an Oracle table
    - a Visual Basic script for export from Active Directory
    - a table in my database
    - a SQL*Loader Control-file
    - a command-file to start the SQL*Loader
    Now I can schedule the vsb-script and the command-file to get my information in an Oracle table. This works fine for me.
    Just to share my scripts:
    I made a Visual Basic script to make an export from my Active Directory to a CSV-file.
    'Export_ActiveDir_users.vbs                              26-10-2006
    'Script to export info from MS Active Directory to a CSV-file
    '     Accountname, employeeid, Name, Function, Department etc.
    '       Richard de Boer - Wetterskip Fryslan, the Nethterlands
    '     samaccountname          Logon Name / Account     
    '     employeeid          Employee ID
    '     name               name     
    '     displayname          Display Name / Full Name     
    '     sn               Last Name     
    '     description          Description / Function
    '     department          Department / Organisation     
    '     physicaldeliveryofficename Office Location     Wetterskip Fryslan
    '     streetaddress          Street Address          Harlingerstraatweg 113
    '     l               City / Location          Leeuwarden
    '     mail               E-mail adress     
    '     wwwhomepage          Web Page Address
    '     distinguishedName     Full unique name with cn, ou's, dc's
    'Global variables
        Dim oContainer
        Dim OutPutFile
        Dim FileSystem
    'Initialize global variables
        Set FileSystem = WScript.CreateObject("Scripting.FileSystemObject")
        Set OutPutFile = FileSystem.CreateTextFile("ActiveDir_users.csv", True)
        Set oContainer=GetObject("LDAP://OU=WFgebruikers,DC=Wetterskip,DC=Fryslan,DC=Local")
    'Enumerate Container
        EnumerateUsers oContainer
    'Clean up
        OutPutFile.Close
        Set FileSystem = Nothing
        Set oContainer = Nothing
        WScript.Echo "Finished"
        WScript.Quit(0)
    Sub EnumerateUsers(oCont)
        Dim oUser
        For Each oUser In oCont
            Select Case LCase(oUser.Class)
                   Case "user"
                        If Not IsEmpty(oUser.distinguishedName) Then
                            OutPutFile.WriteLine _
                   oUser.samaccountname      & ";" & _
                   oUser.employeeid     & ";" & _
                   oUser.Get ("name")      & ";" & _
                   oUser.displayname      & ";" & _
                   oUser.sn           & ";" & _
                   oUser.description      & ";" & _
                   oUser.department      & ";" & _
                   oUser.physicaldeliveryofficename & ";" & _
                   oUser.streetaddress      & ";" & _
                   oUser.l           & ";" & _
                   oUser.mail           & ";" & _
                   oUser.wwwhomepage      & ";" & _
                   oUser.distinguishedName     & ";"
                        End If
                   Case "organizationalunit", "container"
                        EnumerateUsers oUser
            End Select
        Next
    End SubThis give's output like this:
    rdeboer;2988;Richard de Boer;Richard de Boer;de Boer;Database Administrator;Informatie- en Communicatie Technologie;;Harlingerstraatweg 113;Leeuwarden;[email protected];;CN=Richard de Boer,OU=Informatie- en Communicatie Technologie,OU=Afdelingen,OU=WFGebruikers,DC=wetterskip,DC=fryslan,DC=local;
    tbronkhorst;201;Tjitske Bronkhorst;Tjitske Bronkhorst;Bronkhorst;Configuratiebeheerder;Informatie- en Communicatie Technologie;;Harlingerstraatweg 113;Leeuwarden;[email protected];;CN=Tjitske Bronkhorst,OU=Informatie- en Communicatie Technologie,OU=Afdelingen,OU=WFGebruikers,DC=wetterskip,DC=fryslan,DC=local;I made a table in my Oracle database:
    CREATE TABLE     PG4WF.ACTD_USERS     
         samaccountname          VARCHAR2(64)
    ,     employeeid          VARCHAR2(16)
    ,     name               VARCHAR2(64)
    ,     displayname          VARCHAR2(64)
    ,     sn               VARCHAR2(64)
    ,     description          VARCHAR2(100)
    ,     department          VARCHAR2(64)
    ,     physicaldeliveryofficename     VARCHAR2(64)
    ,     streetaddress          VARCHAR2(128)
    ,     l               VARCHAR2(64)
    ,     mail               VARCHAR2(100)
    ,     wwwhomepage          VARCHAR2(128)
    ,     distinguishedName     VARCHAR2(256)
    )I made SQL*Loader Control-file:
    LOAD DATA
    INFILE           'ActiveDir_users.csv'
    BADFILE      'ActiveDir_users.bad'
    DISCARDFILE      'ActiveDir_users.dsc'
    TRUNCATE
    INTO TABLE PG4WF.ACTD_USERS
    FIELDS TERMINATED BY ';'
    (     samaccountname
    ,     employeeid
    ,     name
    ,     displayname
    ,     sn
    ,     description
    ,     department
    ,     physicaldeliveryofficename
    ,     streetaddress
    ,     l
    ,     mail
    ,     wwwhomepage
    ,     distinguishedName
    )I made a cmd-file to start SQL*Loader
    : Import the Active Directory users in Oracle by SQL*Loader
    D:\Oracle\ora92\bin\sqlldr userid=pg4wf/<password>@<database> control=sqlldr_ActiveDir_users.ctl log=sqlldr_ActiveDir_users.logI used this for a good list of active directory fields:
    http://www.kouti.com/tables/userattributes.htm
    Greetings,
    Richard de Boer

    I have a table with about 50,000 records in my Oracle database and there is a date column which shows the date that each record get inserted to the table, for example 04-Aug-13.
    Is there any way that I can find out what time each record has been inserted?
    For example: 04-Aug-13 4:20:00 PM. (For my existing records not future ones)
    First you need to clarify what you mean by 'the date that each record get inserted'.  A row is not permanent and visible to other sessions until it has been COMMITTED and that commit may happen seconds, minutes, hours or even days AFTER a user actually creates the row and puts a date in your 'date column'.
    Second - your date column, and ALL date columns, includes a time component. So just query your date column for the time.
    The only way that time value will be incorrect is if you did something silly like TRUNC(myDate) when you inserted the value. That would use a time component of 00:00:00 and destroy the actual time.

  • I have my personal music (not purchased from Itunes) stored in two locations, on my PC and on an external HD. How can I find out which directory itunes uses to access this music? I am using Itunes version 11.4.0.18. Thanks

    I have my personal music (not purchased from Itunes) stored in two locations, on my PC and on an external HD. How can I find out which directory itunes uses to access this music? I am using Itunes version 11.4.0.18. Thanks

    Many thanks JEM24 for your help.  Ive just spent the best part of six hundred pounds on a new Sony Rx100m2 compact camera, so I have no interest in the Ipods camera at all really. I doubt Ill be watching many videos on it as Im very lucky in that I have a good Android tablet. Its more as a stock music player that Ill be buying the Ipod for, if indeed I do end up buying one. I dont like the idea of paying the exorbitant amount added for more memory space that Apple along with most other companies charge. In fact I read an article on this very subject just yesterday in the tech section of Flipboard. It stated in the article that in the case of the Iphone  the actual cost of each additional  gigabyte of storage  to Apple et al is something in the order of 60p.. This is certainly not reflected in the price us the customer has to pay at the till.. Its for this reason primarily that Apple in particular, because their products do not allow adding expandable memory of your own in the form of cheap to buy cards, that nobody in their right mind buys the 64gig etc Iphones..I am aware that we are discussing my potential purchase of an Ipod Touch here but you see my point. Many thanks again though for helping me.

  • How do I change the "Default Directory" associated with my subscription?

    I was recently added as an administrator for a client's Azure subscription.  This has caused his account AD to be the default directory I see when I log in.  So every time I log in I have to open the Subscriptions menu and change the FILTER BY
    DIRECTORY option.  How can I make my own directory the default directory when I log in?
    Note: there was an almost identical question back in Dec 2013 and the solution was to have the other user remove you as an administrator.  The marked answer suggested the questioner read some arcane description of Azure subscriptions and Active Directory.
      I need to remain an admin for the other account and the referenced document had nothing useful to say about my problem.
    Anyway, thanks in advance for your help.

    Hi,
     Thank you for posting.
     I hope you find the following link helpful.
     http://itproguru.com/expert/2014/07/change-azure-subscriptionsgo-directly-to-a-specific-subscription-in-windows-azurestep-by-step/
    Regards,
    Nithin Rathnakar.

  • HT201269 how to transfer content from an android Galaxy phone to an iPhone5s?

    How to transfer content from a Galaxy II Android phone to a iPhone5s?

    Alternatively, you can copy photos from Android phone to wireless flash drive and from wireless flash drive to iPad.
    http://www.sandisk.com/products/wireless/flash-drive/

  • How to add content source in office 365 ?

    How to add content source in office 365 , where I can add find Manage Content Sources page to click on New Content Source LInk

    You can't. Only sources available is what is already set up...which is SharePoint/OneDrive4B and Exchange via eDiscovery.
    Thanks,
    Mikael Svenson - Search Enthusiast
    SharePoint MVP/MCPD/P-TSP - If you find an answer useful, please up-vote it.
    http://techmikael.blogspot.com/
    Author of
    SharePoint Search Queries Explained and
    Working with FAST Search Server 2010 for SharePoint

Maybe you are looking for

  • Pls help - colour management suite does not activate

    Have the following problem with the bridge colour management properties opening:- am in Bridge CS4- inside dropdown menu "creative suite-colour management" photoshop and illustrator are installed and in use I cannot open this menu section as I get th

  • 915G combo HDD CD-DVD question

    Hi I have a new 915G combo MB with latest bios etc. Here is the question, i have Boot Hdd on the blue IDE1 as c/s the 2 CD-DVD CD/R-RW on IDE 2 as c/s, in bios it reports Pri master       not detected pri secondary   not detected sec master      not

  • AWR snapshot not generatedand how to compare statistics with a baseline

    01. AWR snapshot not being generated even after setting looks fine 02. compare a captured set of statistics with a baseline. i m not much clear on this, please help as i have this requirement at hand. Thanks a lot in advance.

  • Unable to initialize the VISA library

    /usr/local/vxipnp/linux/NIvisa/NIvisaic     -->          Unable to initialize the VISA library. The VISA Interactive Control utility will exit. Running RHEL 5.11 (32-bit) [root@x74943 ~]# rpm -qa|grep nivisa nivisa-4.5.1-f0 [root@x74943 ~]# rpm -qa|g

  • Using letter templates: how to make left hand column with logo/info repeat?

    Hi all, If you use one of the templates in Pages that has a column down the left-hand side of the page where you can put your company logo and information (e.g. the Modern Photographer Letter), I've noticed that when I do replace it with my info on t