How to search for file in a directory or subdirectories?

I need ur help urgently. I'm currently doing a java project in which the program should be able to do file searching.
For eg. if I key in a.jpg, it should display C:\pictures\a.jpg (a.jpg is stored in a folder called "pictures")
But the problem is that my program is only able to search in the C drive only.
If I move the file into a folder in the C drive, my program cannot detect this.
Can you help me to solve this problem? I'm really looking forward for your reply.
Thanks. Here are the codes.
import java.io.*;
import java.awt.*;
class FindFile
     public static void main(String args[]) throws IOException
          //reads the user input
          BufferedReader userInput;
          while(true)
                    userInput = new BufferedReader(new InputStreamReader(System.in));
                    String s = userInput.readLine();
                    //quits the system               
                    if(s.equals("/quit"))
                         System.exit(0);
                    //if user does not key in anything, prompt msg appear
                    else if(s.equals(""))
                         System.out.println("Command Syntax: java ListFiles <filename>");
                         System.out.println("<filename> - The full name of a file and extension (i.e., test.txt)");
                    else if(userInput != null)
                         String t = "c:";
                         File f = new File(t);
                         String[] files = f.list();
                         char[] qwet;
                         boolean test = false;
                         //check for the file name and compare with the user input
                         for (int i = 0; i < files.length; i++)
                              if(files.equals(s))
                                   System.out.println("");
                                   System.out.println("File Found");
                                   System.out.print("The File Found at This Path: ");
                                   //display the path
                                   System.out.print(f.getAbsolutePath());
                                   System.out.println(files[i]);
                                   test = true;
                                   break;
                         //if file does not exist
                         if(test == false)
                              System.out.println("File Not Found");

well, i think the best solution would be make a recursive search through the directory tree. I don't know if you are familiar to this, but the functions that searches for the file would look like this:
public String searchFile(String name) {
  File[] roots = File.listRoots();   // List all file roots (in windows the different units, c:, d:, etc.)
  for (int i = 0 ; i < roots.length() ; i++) {
    String aux = recursiveSearch(roots, name);
if (aux != null) {   // If the "recursiveSearch" returns something different than null is that the file is founded, so we return the path.
return aux;
return null; // If we get there nothing has been found
private String recursiveSearch(File f, String name) {   // f is the directory to search for the file with name "name"
File[] childs = f.listFiles();
for (int i = 0 ;i < childs.length ; i++) {
if (childs[i].isDirectory()) {  // If that is a directory we search inside
String aux = recursiveSearch(childs[i], name);
if (aux != null) {   // We have found it inside this directory
return aux;
} else {  // Is a regular file
if (name.compareTo(childs[i].getName()) == 0) {   // If the file is what we want we return his path
return childs[i].getCanonicalPath();
// If we get here is because the file is not inside the directory or any subdirectory on it
return null;
You should just call the function searchFile(name) with the name of the file you want to search. If it finds one with this name it will return his absolute path, and if he doesn't the desired file he will return null.
If you don't understand anything just ask.
(Note: i have not tested this code, so can be some mistakes, but it think it is almost correct. mmmhh don't now why, but [ & ] appear in my code as < & >. Just replace them.).
Hope that helps.
Zerjio

Similar Messages

  • How to search for files using wildcards * and ?.

    Hi All,
    I've been searching the forum for a couple of hours now and have been unable to find a good example of how to search a directory (Windows OS) for a file using wildcards * and/or ?. Does anyone out there have a good example that they can share with me?
    Thanks

    Hi All,
    First of all I want to thank everyone for taking the time to respond to my question. All of your responses where greatly appreciated.
    I took the example code that was posted by rkconner, thanks rkconner, and modified it to allow me to search for files in a directory that contain * and/or ?. Yes, I said and/or! Meaning that you can use them both in the same file name, example: r??d*.t* would find readme.txt.
    I've posed my complete and thoroughly document code below. I hope it is very helpful to other as I have searched many forums and spent many hours today trying to resolve this problem.
    Enjoy
    * File Name: WildcardSearch.java
    * Date: Jan 9, 2004
    * This class will search all files in a directory using the
    * asterisk (*) and/or question mark (?) as wildcards which may be
    * used together in the same file name.  A File [] is returned containing
    * an array of all files found that match the wildcard specifications.
    * Command line example:
    * c:\>java WildcardSearch c:\windows s??t*.ini
    * New sWild: s.{1}.{1}t.*.ini
    * system.ini
    * Command line break down: Java Program = java WildcardSearch
    *                          Search Directory (arg[0]) = C:\Windows
    *                          Files To Search (arg[1]) = s??t*.ini
    * Note:  Some commands will not work from the command line for arg[1]
    *        such as *.*, however, this will work if you if it is passed
    *        within Java (hard coded)
    * @author kmportner
    import java.io.File;
    import java.io.FilenameFilter;
    public class WildcardSearch
         private static String sWild = "";
          * @param args - arg[0] = directory to search, arg[1] = wildcard name
         public static void main(String[] args)
              String sExtDir = args[0]; // directory to search
              sWild = args[1];   // wild card to use - example: s??t*.ini
              sWild = replaceWildcards(sWild);
              System.out.println("New sWild: " + sWild);
              File fileDir = new File(sExtDir);
              File[] arrFile = fileDir.listFiles(new FilenameFilter()
                   public boolean accept(File dir, String name)
                        return (name.toLowerCase().matches(sWild));
              for (int i = 0; i < arrFile.length; ++i)
                   System.out.println(arrFile.getName());
         }     // end main
         * Checks for * and ? in the wildcard variable and replaces them correct
         * pattern characters.
         * @param wild - Wildcard name containing * and ?
         * @return - String containing modified wildcard name
         private static String replaceWildcards(String wild)
              StringBuffer buffer = new StringBuffer();
              char [] chars = wild.toCharArray();
              for (int i = 0; i < chars.length; ++i)
                   if (chars[i] == '*')
                        buffer.append(".*");
                   else if (chars[i] == '?')
                        buffer.append(".{1}");
                   else
                        buffer.append(chars[i]);
              return buffer.toString();
         }     // end replaceWildcards method
    }     // end class

  • Please answer. how to search for files

    Hi,
    We need an integration with SAP. They send us files in the format: yyyymmddhhmiss.atv
    For example we receive following files:
    20050503101115.atv
    20050504101115.atv
    20050505101115.atv
    So, we dont know how to search for all files with extensions ".atv" in the directory.
    We are using PLSQL. Is there some way to resolve with UTL_FILE?
    Any other suggestion?

    A possibility:
    In sqlplus, issue a HOST command to list the files to a file:
    ls *.atv &gt; atv_dir.txt
    Then use utl_file to read atv_dir.txt and parse it for the file names.
    You could put the filenames in a pl/sql table and use that as loop control.

  • How to search for file in jsp page

    i need help on how to search for a file in a folder where there is a lot of subfolder.like how u search in a document in windows. i need a complete codes in jsp page.
    thank you in advance.
    Message was edited by:
    n_dilah

    no i need to do a search engine in jsp page which is the j2ee.
    i type smth than tat file from any folder will appear the same way when u need to search your file in a document in windows.
    well can u nice people tell me where i can get the codes bcos i stinks when it come to programming.
    thank you very very very much.

  • How to search for data in active directory

    if i have an administrator priviledge, how can i search for user's data if i know his username from active directory.

    What form do you have the user's name in ?
    ANTIPODES\alberteString searchFilter = "(&(objectClass=user)(samAccountName=alberte))";[email protected] searchFilter = "(&(objectClass=user)(userPrincipalName=[email protected]))";Albert EinsteinString searchFilter = (&(objectClass=user)(givenName=Albert)(sn=Einstein))";or using Ambiguous Name Resolution (anr)String searchFilter = "(&(objectClass=user)(anr=Albert Einstein))";or it's even clever enough to useString searchFilter = "(&(objectClass=user)(anr=Einstein Albert))";

  • How to search for file within compressed file

    I hope i can explain this correctly, I apologize in advance.
    What is the command to search for a file that may/may not exist within another compressed file?
    Situation is that I have a cron job that compresses the files in a folder on a scheduled date. I now need to search for a file that may exists in one of the several compressed files, which was a result of the cron job.
    Thanks in advance

    There's an open source utility called zgrep. You can probably get it from http://www.sunfreeware.com/ .
    HTH,
    Roger S.

  • How to search for files everywhere?

    When I use Apple-F to find files, apparently only some folders are searched, even when I have "This Mac" selected. For example, I cannot seem to find anything in ~/Library. Can I force it to search all folders that I have permission to view? Thanks for any help!

    to search those folders you need to include system files in your search.
    After you enter command+f to bring up a search window, click on "Kind" and scroll to "other". You'll get a popup window will all possible search parameters. Choose "system files" and set it to "include". To see even more items, select "Spotlight items" and include those.

  • How do I exclude directories from Finder search results? I'm trying to find the biggest FILES on my computer and it keeps showing me "Macintosh HD" as the biggest, how can I search for files of type "NOT folder/directory"?

    Basically I've lost 10GB of free space over the last few weeks so my plan was to search for files modified in the last 2 weeks in order to figure out which ones are big and where that space went.
    So I open finder, go to "File > Find", and enter a search:
    Modified > In the last 2 weeks
    All fine so far.
    Problem is, it's showing whole directories as results. Which essentially means that when I order the list by size, Macintosh HD is at the top, followed by "Users", then "Applications", then one of my bigger movie files, then "Library", etc.
    How can I do a search which will ignore folders? I want individual files. Knowing that Macintosh HD is the biggest item on my computer and was modified in the last 2 weeks is utterly useless to me.
    Older versions of Finder in OS 9 had a feature where you could search for "files, whose type "IS NOT" folder", but OS X doesn't seem to have such a feature.
    Can anyone help?

    How much free space is on the HD, where has all the space gone?
    OmniDiskSweeper is likely the easiest/best, and is now free...
    http://www.omnigroup.com/applications/omnidisksweeper/download/

  • How To Search For a Specific File name?

    Hello Everybody
    How To Search For a File Like NewFile.txt in a Root Like C:\\
    And If The File Is Found Open It And Write In It?

    http://forum.java.sun.com/thread.jspa?threadID=5194090&messageID=9763314

  • When importing files, my view window to search for files is really small, how do I make it bigger so I can actually search for files?

    When importing files, my view window to search for files is really small, how do I make it bigger so I can actually search for files?

    How big this is depends on the size of your screen. On a 13" it is really small. But you can improve things a bit. Click the green button to make the import window fill the screen.
    Drag the area between the file list and the preview area up or down to increase one or the other:

  • I have a external hard drive connected, Finder will not let me search for files in the external hard drive how do i search in a hard drive

    i have a external hard drive connected, Finder will not let me search for files in the external hard drive how do i search in a hard drive

    What are you using to search? You should be able to search any drive in from the Finder. If you're having trouble, try "EasyFind" from the App Store (free). You can search any volumes with it.
    Clinton

  • How can I search for files with more than one keyword?

    I´ve created some keywords, and some files in my folder are tagged with two, three or more keywords.
    Is there a way to search for files using more than one keyword on the search field?
    Thanks!

    Use the Find command (menu Edit) and in criteria at the right side is a plus sign to add another criteria and set it to your custom wishes.
    make a choice in results and you should be OK

  • How can I search for files on multiple servers at one time?

    When I hit command+F, and use spotlight to search for files, I'm only given the opportunity to search for those files in three places: "This Mac", "Shared", and then the server or external HD that is mounted. However, in the past I was able to check a box for all mounted/connected servers/HDs, and then do a search in all of them at the same time. I CAN'T FIND THIS OPTION IN LEOPARD AND IT IS ANNOYING ME BIG TIME.
    Hopefully there is a simple solution that I've overlooked.
    Please help!

    no

  • How can I: Search for files "not in catalog"

    Is there a way to search for files/photos on my hard drive that are *NOT* already in my catalog?
    (a) I can do a mass search to find all photos on my hard drive.
    (b) And there is a reconnect feature - for all entries in catalog with a missing/invalid link, look for the file that matches best.
    But I'd like to have Elements find photos that I have not added to the catalog.
    That is, do (a), but check each one to see if it is already added.
    Is there a way to do that?
    Thanks,
      -ceej

    What you want to achieve by finding those files?
    In folder view you can see the folder which have no media files in Organizer.
    If you import all the files form all the drives on your system, by deafult you will see files just imported into catalog. That means, just after import ou will have the files which were not in your catalog :-)
    I know my  answer could be confusing for you, but it will make sense if you know what happens after import in Organizer...

  • Why does it keep searching for files

    When I record in another studio save files to HD get to another stuidio pull up song it keeps asking to search for files.

    Well that's how the file structure works. If you record to a folder located e.g. in ~/Music/Logic8/Soundtracks/title/cue1/Audio files/ and move the stuff to another computer those files must be located in exactly the same directory on the new computer in order to show up in your project. If you look into the bin you see that each file has a description where it's location is. If it's not located there Logic can't find it and asks you to locate it.

Maybe you are looking for

  • How do I get a video track in Logic Pro 9?

    I'm trying to sync a video I have recorded in Photo Booth with the music I recorded via my mixer into Logic Pro 9. I have tried dragging the video into Logic and it only gives me options like bring in the audio (also another issue is that the audio h

  • One down payments for two customers

    I have one payment received for one bank account and it is for the two customers. Ex : Down payment received  USD 100 Customer A                             USD 75 Customer B                             USD 25 How can I post these values for both of

  • Where Can I Download the Chalk 11 Pixel Brush?

    Hello all, I have loaded all the available brushes in Photoshop CC, but I can't find the "Chalk 11px Brush."  Can anyone tell me where I can locate and download this brush? Thanks!

  • Tips for a NEW mac user

    So this is my new thread that started at http://discussions.apple.com/thread.jspa?messageID=8165450#8165450 I just learned that I can use most any mouse that has right click on my newish iMac G4. It also helps to know that I can control click / contr

  • Not Enough Memory error when updating a podcast??

    I am having difficulties with the Radio GoDaddy podcast. Last week when I subscribed, I entered the URL and iTunes downloaded the latest episode, no problem. They release a new episode every Wednesday. So this morning I clicked the Update button and