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!

Similar Messages

  • 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

  • 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?

  • How to list all files in my system

    Hi there,
    I want to list all files in my system. My system is Windows XP, can anybody help me please? Any can you recommend me if java is suit for such processing?
    Thx in advance.

    public void showFilesIn(File dir) {
        File[] files = dir.listFiles();
        for (int i = 0 ; i < files.length ; i++)
            if (files.isDirectory())
    showFilesIn(files[i]);
    else
    System.out.println(files[i]);
    showFilesIn(new File("C:\\"));
    notice that it won't show directories, but only files

  • List all file names in a directory

    Hello everybody,
    I need to write a script in PL/SQL (oracle 10g) that lists all filenames in a specific directory on a client machine and import the files into the database (xml files). After the file is imported they have to be removed.
    I was searching for a solution for this because I have never come accross a challenge like this.
    What I found was that I could use the procedure dbms_backup_restore.searchfiles of the SYS schema.
    Now I need to know how this procedure works. There is very little documentation available.
    Can I give the procedure a folder name on my client computer that has the xml files and let the procedure list these files?
    Can someone please help me with this. I haven't got a clue.
    Thanks in advance.
    regards,
    Mariane

    Hello Justin,
    Thank you for your reply.
    You have just confirmed what I already was thinking: that the server cannot read files from the client.
    I haven't got a client application running to do this. My customer wants me to write a script in PL/SQL that enables users to run an import of xml files in the database by giving in a directory name on the client.
    I told my customer that they have to put the xml files on a server directory. Should that always be the server where the database resides on?
    Is there another way to solve this request?
    Thanks in advance.
    regards,
    Mariane

  • How to list all files and directories in another directory

    I need to be able to list all the directories and files in a directory. I need to write a servlet that allows me to create an html page that has a list of files in that directory and also list all the directories. That list of files will be put into an applet tag as a parameter for an applet that I have already written. I am assuming that reading directories/files recursively on a web server will be the same as reading directories/files on a local system, but I don't know how to do that either.

    Hi,
    Here is a method to rotate through a directory and put all the files into a Vector (files).
          * Iterates throught the files in the root file / directory that is passed
          * as a parameter. The files are loaded into a <code>Vector</code> for
          * processing later.
          * @param file the root directory or the file
          *         that you wish to have inspected.
         public void loadFiles(File file) {
              if (file.isDirectory()) {
                   File[] entry= file.listFiles();
                   for (int i= 0; i < entry.length; i++) {
                        if (entry.isFile()) {
                             //Add the file to the list
                             files.add(entry[i]);
                        } else {
                             if (entry[i].isDirectory()) {
                                  //Iterate over the entries again
                                  loadFiles(entry[i]);
              } else {
                   if (file.isFile()) {
                        //Add the file
                        files.add(file);
    See ya
    Michael

  • How to list all files of an ibook in the OPF manifest?

    I have this message error when i DELIVERED my iBooks with I Tunes Producer.
    ERROR ITMS-9000: "A5809-7_Math_Venture_3rd_Operations.ibooks: The book asset contains file(s) not listed in the OPF manifest: A5809-7_Math_Venture_3rd_Operations.ibooks:/OPS/assets/widgets/Activite? 1 english-1.kpf/images-1/s1.a.jpeg.  All files must be listed in the OPF manifest, or there is no way to confirm that they are intended for distribution. For more information refer to http://idpf.org/epub" at Book (MZItmspBookPackage)
    Like it is written, All files must be listed in the OPF manifest, or there is no way to confirm that they are intended for distribution.
    What that means?
    Need help please, for the last step before publishing my first book on iBookStore :-(
    Tx

    Hi, I've got the same issue here, there was something to do to get it fixed?
    I've read that my file (i suppouse the .ibooks file) should be named as the cover file (i suppouse the .jpg that shows the cover)
    Well, i renamed almost all files: the .iba file, the .ibooks and the .jpg cover file with the same name: Jalisco Auge de México (right, with accents)
    Then, in the list of issues i got this issues above the ones as listed by you:
    1: Apple's web service operation was not successful
    2: Unable to authenticate the package: (package number.itmsp)

  • 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.

  • How to list all files in directories

    Here's what I'd like to do, and I know there's a genius on this forum that knows the answer:
    Let's say I burn a disc with lots of folders and files. How could I see a list of all those folders with their included files in one easy to read place? Like, could I go to Terminal and list the contents of the disc in kind of a directory tree sorta layout that could be copied to a text document?
    I have several dozen discs of data I've burned over the years, and when I want to find a certain file, I have to open the disc and manually click thru all the folders to see their contents until I find what I'm looking for. I'd like to make an "index" of each disc so I can find things faster, or better, list the folders/files in a text file I could save, 1 per burned disc. Does this make sense. Is this do-able?

    That works pretty sweet, too. As with other techniques, a lot of output to filter thru, hard on the eyes, might kill a printer, I dunno. As far as the output itself... what is this command asking for, in English, like, "Ms. Terminal application: please list ..." What? (the " -lR part)
    And the results:
    /Users/rob/Desktop/Websites/ARP-new content,May 2008/arp new ens/new vert en:
    total 752
    -rw-r--r-- 1 rob rob 48593 Jun 3 16:28 608v1_en.jpg
    What's the "total 752" mean?
    What's the "1" in front of the "rob rob" part?
    Apparently the date only shows the year if it's other than this year?
    I noticed Terminal doesn't like spaces in path names, like "/Users/rob/Desktop/My Best Folder Ever",
    should I rename everything like "MyBest_FolderEver", or is there a workaround for name spaces? Just some curiosity. Do you know of a concise, easy to digest guide to commands in the Terminal? It's something I'd like to learn more about. And thanks for the DIRECT answer to my original post.

  • How to list all filename in excuteable jar file?

    Hi there,
    i've been googling around for hours, but found no good answer :(
    i want listing all file name in my excuteable jar file
    Firstly, i use
    File f = new File("/sounds");
    String[] filenames = f.list();
    and use these filenames to load some resouces from url
    //ex
    URL url = getClass().getResource("/sounds/"+filenames);
    No problem occurs when i run it normally
    but when I put it in excuteable jar file, NullPointerException appears
    i think it's because : "File f = new File("/sounds");" doesn't work in jar file (somehow, i don't know why too)
    is there any alternative way to listing all filename in this situation?
    thanks in advance

    There are jar handling classes in the standard library under java.util.jar. I think JarFile is the one you want.
    Hower it's not good practice to list jar contents in order to read resources. It's better to have some kind of resource file in the jar which lists your sounds or whatever. A simple text file with one file name per line suffices.

  • 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 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

  • List all files in a directory, not including the sub directories if any

    Hi,
    I have been looking around php.net for a bit and can not work
    out how i list the files that are in a directory i.e.
    www.site.com/directory/
    I would like the names of each file to be placed in an array,
    but not to have the sub directories in this list should there be
    any.
    I was given some code a while ago that done this but it
    listed the sub directories and i would like them not in this list.
    I do not have this code anymore and do not know where i got
    it, so i can not get it amended to what i need.
    please can someone tell me what line of code i should be
    using.
    thank you in advance for your help.

    (_seb_) wrote:
    > not very clever wrote:
    >> Hi,
    >>
    >> I have been looking around php.net for a bit and can
    not work out how
    >> i list the files that are in a directory i.e.
    >>
    >> www.site.com/directory/
    >>
    >> I would like the names of each file to be placed in
    an array, but not
    >> to have the sub directories in this list should
    there be any.
    >>
    >> I was given some code a while ago that done this but
    it listed the
    >> sub directories and i would like them not in this
    list.
    >>
    >> I do not have this code anymore and do not know
    where i got it, so i
    >> can not get it amended to what i need.
    >>
    >> please can someone tell me what line of code i
    should be using.
    >>
    >> thank you in advance for your help.
    >>
    >>
    >>
    >
    > The follwoing PHP code will do just that. Just replace
    "pathToFolder"
    > with the path to your folder.
    > I made the list of files also link to each file. Just
    remove the link
    > echo if you don't them to be links.
    >
    > <?php
    > // FUNCTION TO LIST FILES:
    > function listFiles($path){
    > if($handle = opendir($path)){
    > while(false !== ($file = readdir($handle))){
    > if (is_file($path.'/'.$file) &&
    !preg_match('/^\./',$file)){
    > $files_array[]=$file;
    > }
    > }
    > }
    > return($files_array);
    > }
    > $path = 'pathToFolder';
    >
    > // CALL THE FUNCTION:
    > $files_array = listFiles($path);
    > foreach($files_array as $file){
    > echo '<p><a
    href="'.$path.'/'.$file.'">'.$file,'</a></p>';
    > }
    >
    > ?>
    >
    I spotted one error:
    foreach($files_array as $file){
    echo '<p><a
    href="'.$path.'/'.$file.'">'.$file,'</a></p>';
    should be:
    foreach($files_array as $file){
    echo '<p><a
    href="'.$path.'/'.$file.'">'.$file.'</a></p>';
    (a dot after $file, not a coma)
    seb ( [email protected])
    http://webtrans1.com | high-end web
    design
    Downloads: Slide Show, Directory Browser, Mailing List

  • How to create Dynamic Selection List containg file names of a directory?

    Hi,
    I need a Selection List with a Dynamic List of Values containing all file names of a particular directory (can change through the time).
    Basically, I need an Iterator over all file names in a directory, which could be used for Selection List in a JSF form.
    This iterator has nothing to do with a database, but should get the names directly from the file system (java.io.File).
    Can anybody tell me how to create such an iterator/selection list?
    I am working with JDeveloper 10.1.3.2, JSF and Business Services.
    Thank you,
    Igor

    Create a class like this:
    package list;
    import java.io.File;
    public class fileList {
        public fileList() {
        public String[] listFiles(){
        File dir = new File("c:/temp");
        String[] files = dir.list();
        for (int i = 0; i < files.length; i++)  {
                System.out.println(files);
    return files;
    Right click to create a data control from it.
    Then you can drag the return value of the listFiles method to a page and drop as a table for example.
    Also note that the Content Repository data control in 10.1.3.2 has the file system as a possible data source.

Maybe you are looking for

  • Problem for Oracle 8.1.6 installation on Turbo Linux 7.0 platform

    I meet problem when installing Oracle 8.1.6 on Turbo Linux 7.0 system. I successfully set environmental variables and accessed K.D.E interface. The installation blocked at 80% at “Database Creation Process” window. I have tried two times. Both blocke

  • Convert sql_Varient to integers

    i want to convert the Server_Name value from actual server name to 1 or 2 based on output, which i am already able to do in the code below,now i want to convert the data type of column "Server_Name" to integer after updating the values to 1 or 2pleas

  • Standrad Report For PP

    Plz tell me stnadrad report for work center wise total machine and labour hours and production.

  • Job opening oracle financials consultant - permanent postion

    Hi All oracle EBS experts, We are looking for an oracle ebs r12 financial consultant with atleast 4-5 years experience, for a permanent position in a government sector in middle east. Please send me your resumes to [email protected] Candidates alread

  • ODI Hyperion Planning Reverse Transaction The Screen freeze and Hang

    Hi, There is a problem with reverse transaction via RKM Hyperion Planning KM. In desinger application I will click reverse button, the application is hang up and the screen is freezed. I completed the setup steps. How can be solved the problem? thank