Search through files in a directory

How do I get a list of the files in a directory? I am aware of JFileChooser but it is not what I am looking. I need to search the contents of the xml files in the directory. I can do this with one file but need to do it with them all.

// where files in subdirectory \files below the application directory
File dir = new File(".\\files\\");
  if(dir.exists()){
    File[] list = dir.listFiles();
    for (int i = 0; i < list.length; i++){
      String fileName = list.toString();
int iPtr = fileName.lastIndexOf("\\");
int jPtr = fileName.indexOf(".xml",0);
if (jPtr>-1) {
String longName = fileName;
String shortName = fileName.substring(iPtr + 1, jPtr);
// file name in short name

Similar Messages

  • 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

  • Give a handmake function to search all files in the directory.

    To scan drive, folder, ets.
    I maked this, but my function is big bleep, a devil will break his legs here.
    Need small workable solution.
    Attachments:
    function.txt ‏7 KB

    Sergey,
    Here is an example file which looks through every file in a directory.http://zone.ni.com/devzone/cda/epd/p/id/2157
    It should save you some time if you are having issues with your code. 
    Regards,
    Kyle Mozdzyn
    Applications Engineering
    National Instruments
    Regards,
    Kyle M.
    Applications Engineering
    National Instruments

  • How to iterate through files in a directory in real time?

    I have a program where users can write RPN equations into txt files so that the number and type of equations are completely customizable at run time.  I need to be able to iterate through .txt files in an Equations folder to load the equations into memory.  How can I do this in real time?
    I know I could make the files eq 1.txt through eq 2.txt and iterate through until one doesn't exist, but my standard method has been to name the filename the same as the equation name.  Either way works.
    Thank you.
    Michael Chadwell
    Department of Engine and Vehicle R&D
    Southwest Research Institute

    Hi Michael,
    You could also use the GetFirstFile and GetNextFile functions that come built into CVI. These functions should allow you to iterate through the files in a directory.
    GetFirstFile: http://zone.ni.com/reference/en-XX/help/370051Y-01/cvi/libref/cvigetfirstfile/
    GetNextFile: http://zone.ni.com/reference/en-XX/help/370051Y-01/cvi/libref/cvigetnextfile/
    Hope this helps,
    Kevin

  • Need help writing a script to traverse through files in a directory

    I want to go through a directory and sub directories and convert files into jpg ones
    I have this code I've been using: mkdir jpegs; sips -s format jpeg *.png --out jpegs
    This is great for one directory at a time
    But, what I want is to apply this to all sub directories, create a jpeg directory in each of the sub directories and then create jpg's and put them in there
    I'm not sure where to start
    Should I be looking for 'scripting in linux'?
    Thanks
    Omar

    Hello
    You may also try something like this. Set DIR to the root directory to start the search.
    #!/bin/bash
    #     convert png to jpeg and put jpeg in jpegs sub-directory
    DIR=~/Desktop/test
    while read -d $'\0' f
    do
        d=${f%/*}/jpegs
        [[ -d "$d" ]] || mkdir "$d"
        sips -s format jpeg "$f" --out "$d"
    done < <(find "$DIR" -type f -iname '*.png' -print0)
    In case, here's an AppleScript wrapper:
    set f to (choose folder with prompt "Choose root folder to process")'s POSIX path
    if f ends with "/" then set f to f's text 1 thru -2
    do shell script "/bin/bash -s <<'EOF' -- " & f's quoted form & "
    #     convert png to jpeg and put jpeg in jpegs sub-directory
    DIR=\"$1\"
    while read -d $'\\0' f
    do
        d=${f%/*}/jpegs
        [[ -d \"$d\" ]] || mkdir \"$d\"
        sips -s format jpeg \"$f\" --out \"$d\"
    done < <(find \"$DIR\" -type f -iname '*.png' -print0)
    EOF"
    Regards,
    H

  • Search Through File with OPENCSV

    All,
    I am searching thru a .csv file for using regular expressions. I am looking for a patter that looks like a date: mm/dd/yyyy.
    I search for the pattern while reading my .csv file. Since I am in a loop, I can't get a permanent handle on the search result. How can I get a permanent handle on it?
    When I come out the loop, the date is empty or null.
    How can I get the one occurrence, and save it?
    Code:
    package mybeans;
    import org.apache.regexp.*;
    import java.util.LinkedList;
    import ClientDataProc.Logging;
    import ClientDataProc.BalancesDataClass;
    import ClientDataProc.ControlsAccess;
    import au.com.bytecode.opencsv.CSVReader;
    import java.util.List;
    import java.io.*;
    import java.io.FileReader;
    import java.io.IOException;
    public class CSVBalances {
    static String find="";
    //lets get headers from config file.
    String[] headers;
    String finalDate ="";
    static String date ="";
    private static Logging log = new Logging();
    public static void main(String[] args) throws IOException {
              CSVBalances test = new CSVBalances();
              test.readData("Cash.csv", "royal.csv");
              System.out.println("From main" +date);
         public LinkedList<BalancesDataClass> readData(String filename, String config)throws IOException {
              ControlsAccess controls = new ControlsAccess(log);
              BalancesDataClass balances = new BalancesDataClass(controls, filename, -1,log);
              LinkedList<BalancesDataClass> list = new LinkedList<BalancesDataClass>();
              //lets get the date out of the file.
              CSVReader readerDate = new CSVReader(new FileReader(filename));
              String [] nextLineDate;
              while((nextLineDate = readerDate.readNext()) != null){
                   for(int i = 0;i<nextLineDate.length;i++){
                   finalDate = findDate(nextLineDate);
                   if(finalDate != null || finalDate != ""){
                        date = finalDate;
                        System.out.println(date);
                        break;
                   break;
                   //now we read the data file.
                   CSVReader reader = new CSVReader(new FileReader(filename),',','\"',3);
                   String [] nextLine;
                   //read the configuration file.
                   File configFile = new File(config);
                   CSVReader configReader = new CSVReader(new FileReader(configFile));
                   while((headers = configReader.readNext()) != null){
                        //lets find the date in the file:
                        while ((nextLine = reader.readNext()) != null) {
                        for(int h =0; h<headers.length;h++){
                             System.out.println(headers[h] + nextLine[h]);
                             //add to our objects BalancesDataClass/ClientDataClass.
                             balances.saveData(headers[h], nextLine[h]);
                   }return list;
         private static String findDate(String part){
              String date="";
              String pattern = "[0-9][0-9]" + "/" + "[0-9][0-9]" + "/" + "[0-9][0-9]";
              RE r = new RE(pattern);
              if(r.match(part)){
                   //System.out.println("The match is: " + r.getParen(0));
                   date = r.getParen(0);
              return date;
    public String getDate(){
         return this.date;

    Here is the snippet of my code. Can someone please take a look at it.
    while ( (dbRecord = dis.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(dbRecord, ":", false);
    Vector row = new Vector();
    String lineTemp;
    while (st.hasMoreTokens()) {
    if (st.nextToken().trim().equalsIgnoreCase(userinput)) {
    //System.out.println(dbRecord);
    StringTokenizer tempst = new StringTokenizer(dbRecord, ":", false);
    while (tempst.hasMoreTokens()){
    row.addElement(tempst.nextToken());
    dataVector.addElement(row);
    }

  • Can we search different files in a directory!!!

    Hello!!!
    I have a simple question.Suppose we have a directory containingg different types of files,say zip,rar,txt,gif etc.Now if we want to show only txt files to client then how to do that.
    I am using jsp.
    I want to show my client only text files contained in that directory.
    Please help me how to implement this.
    Thanks in advance.

    Thanks man!!!
    Atleast i got the enough information that kept me going.
    These forums rock mam!!!

  • 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

  • Webgate installation - not able to find .cgi file in bin directory

    Hi friends,
    I am trying to install webgate on ohs server (after webpass installation). But as told in installation document for webgate, we need to configure the webgate by giving relative path to dll or cgi file in bin directory.
    But when I tried to search .cgi file in bin directory, there is no cgi file there, there is only webgate.dll file.
    Please tell me what exactly is the issue I am facing here?
    Thanks in Advance,
    Amit

    Hi,
    Let me know which document you are following. While installing webgate, we need to provide the path configuration file of webserver. In your case, it is httd.conf.
    Regards
    GK Goalla

  • Read a file in the directory

    Hai,
    I am looking some Hint code/ forum discussion for
    search a file in a directory.
    Any Idea.

    Check out the File API.

  • Audit directory and searching through the logs for deleted file

    Windows Server 2003
    I have found article http://whatevernetworks.com/?p=108
    And in description of this article is: to found deleted files in auditing directory I have to found event 560.
    But I have about 60 000 events.
    My file abcd.txt is missing and I have to find who delete it, but I cant click 60 000 times to find it.
    Moreover most of that event looks like its objcect open not object deleted.
    How to find this particular?
    Event Type:    Success Audit
    Event Source:    Security
    Event Category:    Object Access
    Event ID:    560
    Date:        2/23/2014
    Time:        11:48:00 PM
    User:        DOMAIN\user
    Computer:    PLWAW1FS00003
    Description:
    Object Open:
         Object Server:    Security
         Object Type:    File
         Object Name:    E:\Temp\download.domain.com\example.zip
         Handle ID:    1788
         Operation ID:    {0,477992664}
         Process ID:    1692
         Image File Name:    C:\WINDOWS\system32\xcopy.exe
         Primary User Name:    user
         Primary Domain:    DOMAIN
         Primary Logon ID:    (0x0,0x1C7D2FA0)
         Client User Name:    -
         Client Domain:    -
         Client Logon ID:    -
         Accesses:    DELETE
                READ_CONTROL
                WRITE_DAC
                WRITE_OWNER
                SYNCHRONIZE
                ACCESS_SYS_SEC
                ReadData (or ListDirectory)
                WriteData (or AddFile)
                AppendData (or AddSubdirectory or CreatePipeInstance)
                ReadEA
                WriteEA
                ReadAttributes
                WriteAttributes
         Privileges:    SeBackupPrivilege
                SeRestorePrivilege
         Restricted Sid Count:    0
         Access Mask:    0x11F019F
    Find fields are: Information/Warning/Error/Succes/Failure
    Event source: DS/IIS/LSA etc...
    Event ID:
    User:
    Computer:
    Description:
    and no filename, or action.
    Maybe I can use powershell to search through the logs?

    Hi,
    You can use Custom View and XML filter to filter specific event logs. Firstly, create a custom view. Then type an XML query to filter by ObjectName (abcd.txt).
    For more detailed information, please refer to the article below:
    Advanced XML filtering in the Windows Event Viewer
    http://blogs.technet.com/b/askds/archive/2011/09/26/advanced-xml-filtering-in-the-windows-event-viewer.aspx
    Regards,
    Mandy
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • How do I search for files greater than 500M in size within a directory?

    I would like to know how to recursively search through a directory and it's subdirectories for files greater than 500M. What is the command for this?
    Thanks!

    Oh my, it's too early...
    You want >500M files, here you go...
    find /path/to/dir -type f -size +524288000c
    **BLUSH**
    To add something useful here, in ksh you can type
    find /path/to/dir -type f -size +$((500*1024*1024))c

  • Looking for a free iOS 4 app that can search through .pdf files or spreadsheets

    Looking for a free iOS 4 app that can search through .pdf files or spreadsheet    
    Thanks

    Hey there
    "pdf creator" for iPad works flawlessly for me working with pdf files
    It takes care of all my needs
    I'm not sure about sending via Wifi or Bluetooth but I send them via e- mail all the time
    Possibly it could handle your needs as well
    Just type it into the App Store search field and the first one that comes up is the one I use
    Jump on over there and read up on it before buying and see if it will help you 
    Hope this helps
    Regards

  • Searching for a file in a  directory

    Hai,
    i am ooking for a code that searches a file( file name's first part is given for example results) in a directory. so search code is going to search a filename like results.csv in the directory.
    any idea?

    Have a look at the [File API|http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html]

  • Search file within a directory

    hi there... i need to search for a file in a directory. but when i execute it, instead of just typing news.txt i need to type C:/news.txt why is that so when i already concat it.. here is the code and thank you in advance.
    public static void main(String[] args) throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
         System.out.println("Enter file to search : ");
    File filename = new File(in.readLine());
    if (filename.exists()){
         String b = ("C:/").concat(filename.getName());
    System.out.println("File name : " + b + " " +"found");
    else{
    Sender sm = new Sender();
              sm.doSend();
    }

    my problem is that when i run the program...i have to type C:/news.txt to search for the file...but this is not i want it to be i want to search by just typing news.txt..understand?? thank you

Maybe you are looking for

  • How to emai more than one person

    hi, can someone please post some code on how to send more than one person the same email, i tried what's below but get an error: //  Send message out as email via JavaMail //  Emails for group 1 String namesOne[] = {"[email protected], [email protected]

  • Photoshop CC 2014 won't open Bridge properly

    I have just installed Photoshop CC 2014. Now, when I pick 'Open in Bridge' from the File Menu it just brings up the Creative CC installer. It asks if I want to use the current version of Bridge or upgrade. Selecting the current version does nothing.

  • In design CS won't open in OSX 10.7. Is there a quick fix vise new purchase?

    In design CS won't open in OSX 10.7. Is there a quick fix vise new purchase? I get a error message that says (you cant open InDesign CS because PowerPC applications are no longer supported).

  • Pop up window : conatin buttons

    Hi friends, I need to generate a pop up window based on a condition. I can use FM POPUP_TO_CONFIRM, but I need follwing values to be displayed on the pop up window. 1)Three variable values 2)PUSH buttons (5 BUTTONS) please help in this regard as soon

  • Photos remain in wrong iPhoto list even after being moved?

    +Mike G.+ +Posts: 297+ +Registered: 15-Nov-2004+ + Photos remain in wrong iPhoto list even after being moved?+ +Posted: 29-Jan-2009 16:56 + Hi, +Has anyone else had this problem? Any workarounds?+ +I have a number of pictures that just show up in the