How to retrieve all files in a given directory?

Hi all,
I am a newbie to Java. I have to retrieve all files in a given directory. The names of the files are not known to me. Only the name of the directory is known. How can I retrieve and read all those files?
Gary

Check out the list and listFiles method: http://java.sun.com/j2se/1.3/docs/api/java/io/File.html

Similar Messages

  • How to list all files in a given directory?

    How to list all the files in a given directory?

    A possible recursive algorithm for printing all the files in a directory and its subdirectories is:
    Print the name of the directory
    for each file in the directory:
    if the file is a directory:
    Print its contents recursively
    else
    Print the name of the file.
    Directory "games"
    blackbox
    Directory "CardGames"
    cribbage
    euchre
    tetris
    The Solution
    This program lists the contents of a directory specified by
    the user. The contents of subdirectories are also listed,
    up to any level of nesting. Indentation is used to show
    the level of nesting.
    The user is asked to type in a directory name.
    If the name entered by the user is not a directory, a
    message is printed and the program ends.
    import java.io.*;
    public class RecursiveDirectoryList {
    public static void main(String[] args) {
    String directoryName; // Directory name entered by the user.
    File directory; // File object referring to the directory.
    TextIO.put("Enter a directory name: ");
    directoryName = TextIO.getln().trim();
    directory = new File(directoryName);
    if (directory.isDirectory() == false) {
    // Program needs a directory name. Print an error message.
    if (directory.exists() == false)
    TextIO.putln("There is no such directory!");
    else
    TextIO.putln("That file is not a directory.");
    else {
    // List the contents of directory, with no indentation
    // at the top level.
    listContents( directory, "" );
    } // end main()
    static void listContents(File dir, String indent) {
    // A recursive subroutine that lists the contents of
    // the directory dir, including the contents of its
    // subdirectories to any level of nesting. It is assumed
    // that dir is in fact a directory. The indent parameter
    // is a string of blanks that is prepended to each item in
    // the listing. It grows in length with each increase in
    // the level of directory nesting.
    String[] files; // List of names of files in the directory.
    TextIO.putln(indent + "Directory \"" + dir.getName() + "\":");
    indent += " "; // Increase the indentation for listing the contents.
    files = dir.list();
    for (int i = 0; i < files.length; i++) {
    // If the file is a directory, list its contents
    // recursively. Otherwise, just print its name.
    File f = new File(dir, files);
    if (f.isDirectory())
    listContents(f, indent);
    else
    TextIO.putln(indent + files[i]);
    } // end listContents()
    } // end class RecursiveDirectoryList
    Cheers,
    Kosh!

  • Showing all files of a given directory

    I'm trying to write a class that shows me all files of a given directory. When a run the class without parameters, everything seems to work fine, however, when I use a parameter that contains the directory, I get the following error:
    java.lang.NullPointerException
         at be.hogelimb.ti.fundamentals.io.IOProgr4.<init>(IOProgr4.java:25)
         at be.hogelimb.ti.fundamentals.io.IOProgr4.main(IOProgr4.java:43)
    Exception in thread "main"
    this is my class without parameters:
    public class IOProgr4 {
    public IOProgr4(){
    File dirName = new File("C:\\Documents and Settings\\FirstName LastName\\My documents\\test");
         if (dirName.exists()){
         if (dirName.isDirectory()){
         File[] dirFiles = dirName.listFiles();
         for (int i = 0; i<dirFiles.length; i++){
         System.out.println(dirFiles);
         else{
         System.out.println("dirName is not a directory");
         else{
         System.out.println("Can'f find directory");
         public static void main(String args[]){
              new IOProgr4();
    You see, it's a very simple class.
    This is my class with parameters :
    public class IOProgr4 {
    String dirString;
    public IOProgr4(String dirString){
    this.dirString = dirString;
    File dirName = new File(dirString);
    if (dirName.exists()){
    if (dirName.isDirectory()){
         File[] dirFiles = dirName.listFiles();
         for (int i = 0; i<dirFiles.length; i++){
         System.out.println(dirFiles[i]);          
         else{
         System.out.println("dirName is not a directory");
         else{
         System.out.println("Can't find directory");
    public static void main(String args[]){
    String dirString = "";
    for (int i = 0; i < args.length; i++){
    dirString += args[i] + " ";
    new IOProgr4(dirString);
    I'm working with Eclipse and my parameter string is the same as the String I've written in the first class, and it's also recognized as a directory. Can anyone tell me why this doesn't work?
    Thanks in advance!!!

    I'm working with Eclipse and my parameter string is
    the same as the String I've written in the first
    class...In the end, it has nothing to do with whether you've hard-coded the directory name versus taken it as a parameter. It must not have been the same value, or it would have worked the same. So your problem lies elsewhere - however, you were given a nice stack trace pointing out the line in your code where it happened. Are you not familiar with a little concept known as debugging?

  • File Utility - Find operation; How to retrieve all files in a folder?

    I am using Find operation of FileUtility service to count the number of files present under a given folder.
    I can not find the correct Regular Expression to match all files.
    The Adobe documentation mentions that * character is default which matches all files/folder within the Directory. However, If I leave * unchanged, I'm getting an error "Incorrect Regular Expression syntax".
    I have tried different combinations, nothing seems worked.
    Can anyone assist me on this?
    Thanks,
    Nith

    Hi,
    You can use the following syntax to get the list of all files:-
    \w*\.\w*
    Yow can alslo go through the following material for details on Regular Expressions:
    http://help.adobe.com/en_US/livecycle/9.0/workbenchHelp/help.htm?content=000582.html
    Thanks

  • How  to read all files  under a folder directory in FTP site

    Hi Experts,
    I use this SQL to read data from a file in FTP site. utl_file.fopen('ORALOAD', file_name,'r');
    But this need to fixed file name in a directory. However, client generate output file with auto finename.
    SO do we have any way to read all file by utl_file.fopen('ORALOAD', file_name,'r');
    We need to read all file info. because client claim for security issue and does not to overwirte output file name,
    we must find a way to read all file in output directory.
    Thanks for help!!!
    Jim

    If you use Chris Poole's XUTL_FTL package, I believe that contains functions that allows you to query the directory contents.
    http://www.chrispoole.co.uk/apps/xutlftp.htm
    Edited by: BluShadow on Jan 13, 2009 1:54 PM
    misread the original post

  • How to read all files' name in a directory and store in a string array?

    as title

    One possibility is to use the listFiles() method, using recursion if you want the files in the sub-directory also. Check API documentation for java.io.File.

  • My music files etc were all located on my old laptop which was stolen. I have just plugged my iphone in to my new computer and it has deleted all my files. Has anybody got any ideas on how to retrieve the files?

    My music files etc were all located on my old laptop which was stolen. I have just plugged my iphone in to my new computer and it has deleted all my files. Has anybody got any ideas on how to retrieve the files?

    WINDOWS?
    Connect the iPod to your PC. If iTunes starts syncing (ie erasing) your music automatically, hit the X in the upper right hand corner of iTunes display, to the left of the search box, to stop it.
    In Control Panel, Portable Media Devices, double-click your iPod.
    In the Tools menu -> Options, in the View Tab, check "Show hidden files and folders."
    Navigate to the Music folder. On my 'pod, the full path is
    Portable Media Devices\NAME of IPOD (F:)\iPod_Control\Music
    Select all the music folders, and drag and drop them into a folder on your hard drive, or directly into iTunes.
    And you're done! The iPod music folder structure is strange and inexplicable, but once you move your files into iTunes you can set it to automatically organize your folder by artist and album to clean that up. (To do this, in iTunes Edit menu, choose Preferences and in the Advanced tab, check "Keep iTunes Music Folder organized."
    might be out of date worth a try

  • How to retrieve all external refereces in a frame maker file without conditional text of hidden

    How to retrieve all external refereces in a frame maker file without conditional text of hidden

    Hi,<br />Finally I found the solution of the above problem.<br />Use following interface-function combination.<br />///////////code start<br />UIDList lst = Utils<IInCopyWorkFlowUtils>()->GetInCopyStories(doc);<br />for(int32 index = 0;index < lst.Length();index++)<br />{<br /><br />UIDRef incopyStory = Utils<IInCopyWorkFlowUtils>()->GetContainingInCopyStory(lst.GetRef(index));<br />if(incopyStory == UIDRef::gNull)<br />{<br />                                             break;<br />}<br />IDataLink * dLink = Utils<IInCopyBridgeUtils>()->QueryDataLink(incopyStory);<br />if(dLink == nil)<br />{<br />     break;<br />}<br />}<br />//////code end

  • Scc question: how can I retrieve all files in 6.1?

    hello
    I have recently upgraded from LV5.1 to 6.1.. In 5.1
    it was possible to retrieve all files of a project
    with scc. When I try to do that in 6.1 (scc provider, select changed files, get latest version..) LV searches
    always in the local work directory for the vi's, but they don't exist, so I have to press "cancel" all the
    time.
    Is there an easier way to retrieve all files of a project at once???
    thanks

    NI support has sent me this VI, replace the original
    VI and it works..
    Attachments:
    Builtin_SCC_Retrieve_sub.vi ‏74 KB

  • How to retrieve full flash solution from WSP if not than how to retrieve ascx files from Template folder in SharePoint 2013 ?

    How to retrieve ascx file from the Template folder in SharePoint2013
    My issue is, I have WSP only so I changed into zip and got my all web parts and also one dll file after that decrypted dll and got some C# code
    mixing with some system generated code but not ascx file that is for front-end part. So my question is how we can retrieve full flash solution if not, at least ascx files So if we were on SharePoint 2010 we could have got those file from __Template__
    folder but It’s on SharePoint 2013 and not able to get ascx.
    If we can do so, than will be easy to get the task to be done
    Suggestions would highly be appreciated. Thanks in Advance.
    Ashish

    Hi Amit,
    you can not move specific changes from Dev to production.
    but you can follow this process to make your workflow as it is as in Dev:
    Create a new workflow on the new list in Product.
    Create at least one step, one condition and one action in this workflow.
    1. In Dev server open your .xomal file as XML and copy the entire contents.
    2.In Production server Open your .xoml file as XML and Paste the entire contents
    3. repeat this operation for the xoml.rules file
    4.Double click the .xoml file for the new workflow to open the workflow in the Workflow Designer and click Check Workflow to verify no errors and then click Finish to ensure the workflow is saved.
    Whenever you need to make changes apply the same.
    Please Mark Answer and Vote me if it will to resolve your issue

  • How to select all files in "user dir" (LastAccessedDirectrory) using applet

    Hi,
    Can anyone tell me " How to select all files in "user dir" (Last Accessed Directrory) using applet"?
    For this which method in applet used?
    Thanks in Advance.

    1) Do you want "user dir" (watever that is) or do you wnat the last accessed directory? Last accessed by what/whom?
    2) Applets can't access the local file sytem, and for good reason, unless they're signed and the client has given permission.

  • How to retrieve all datas that lost when i update my iphone4 to that 6.10 ios. i tried to look at may i tunes in my computer but it seems that i forgot to perform back ups since i purchased this phone 2yirs ago.. pls send me an advice..thank u.

    how to retrieve all datas that lost when i update my iphone4 to that 6.10 ios. i tried to look at may i tunes in my computer but it seems that i forgot to perform back ups since i purchased this phone 2yirs ago.. pls send me an advice..thank u.

    All of the data should be on your computer, simply sync it back.
    If the update was done via iTunes on the computer, the first step in the process is a backup of the device.

  • How to retrieve all users in the portal with UME API

    Hi everybody,
    I would like to know how to retrieve all the users from a portal, which uses LDAP as a source (there are users created in the portal as well)
    My code snippet is :
    IUserFactory userFactory = UMFactory.getUserFactory();
    UserSearchFilter searchFilter = userFactory.getUserSearchFilter();
    searchFilter.setDisplayName("*", ISearchAttribute.LIKE_OPERATOR, false);
    ISearchResult searchResult = userFactory.searchUsers(searchFilter);
    My problem is that with the code above, only the users created in the portal are displayed, and no LDAP users.
    Does someone know how to retrieve all the users whatever is the source?
    Regards
    Renaud

    prakash's code should work.
    however, mine code below doesn't user a search filter. it retrieves everyuser including users like indexadmin etc. Note:
    result.next().toString();
    returns a weird uniqueID used in the portal world.
    getUniqueName()
    gives your the usernames (sAMAccountName in Microsoft AD) people use to logon to the portal.
    try {
      IUserFactory uf = UMFactory.getUserFactory();
      ISearchResult result = uf.getUniqueIDs();
      while (result.hasNext()) {
        String uniqueid = result.next().toString();
        IUser user = uf.getUser(uniqueid);
        String userid = user.getUniqueName();
    } catch(Exception e) {
      //systemout

  • How to select all files in a stack? Control-click doesn't work

    how to select all files in a stack? Control-click doesn't work

    Switch to list or column view. If you must use icon view, instead of Shift-clicking items, click on an empty space near one of them and drag to enclose them.
    (119467)

  • Can anyone tell me how to retrieve all reserved identifiers and keywords in

    can anyone tell me how to retrieve all reserved identifiers and keywords in oracle ???
    i want to know the syntax of query ??

    yes i do , but now i faced problem of JDBC
    thanx for the help , i am able to retrieve the keywords
    actually i want to retrieve the words in java thought JDBC
    my code is
    try ..//
    Vector  keywords =new Vector();
    String sql4=("select * from   V$RESERVED_WORDS");
    ResultSet rs7=stmt6.executeQuery(sql4);
    //  System.out.println("1");
    while(rs7.next())
    keywords.addElement(rs.getString("KEYWORD"));
    ;catch //This is giving following exception
    java.sql.SQLException: Invalid column name

Maybe you are looking for