Java - Search for files in a directory

前端 未结 9 636
予麋鹿
予麋鹿 2020-11-29 05:12

This is supposed to be simple, but I can\'t get it - \"Write a program that searches for a particular file name in a given directory.\" I\'ve found a few examples of a hardc

相关标签:
9条回答
  • 2020-11-29 05:34
    public class searchingFile 
    {
         static String path;//defining(not initializing) these variables outside main 
         static String filename;//so that recursive function can access them
         static int counter=0;//adding static so that can be accessed by static methods 
    
        public static void main(String[] args) //main methods begins
        {
            Scanner sc=new Scanner(System.in);
            System.out.println("Enter the path : ");
            path=sc.nextLine(); //storing path in path variable
            System.out.println("Enter file name : ");
            filename=sc.nextLine(); //storing filename in filename variable
            searchfile(path);//calling our recursive function and passing path as argument
            System.out.println("Number of locations file found at : "+counter);//Printing occurences
    
        }
    
        public static String searchfile(String path)//declaring recursive function having return 
                                                    //type and argument both strings
    
        {
            File file=new File(path);//denoting the path
            File[] filelist=file.listFiles();//storing all the files and directories in array
    
        for (int i = 0; i < filelist.length; i++) //for loop for accessing all resources
        {
            if(filelist[i].getName().equals(filename))//if loop is true if resource name=filename
            {
                System.out.println("File is present at : "+filelist[i].getAbsolutePath());
                //if loop is true,this will print it's location
                counter++;//counter increments if file found
            }
            if(filelist[i].isDirectory())// if resource is a directory,we want to inside that folder
            {
                path=filelist[i].getAbsolutePath();//this is the path of the subfolder
                searchfile(path);//this path is again passed into the searchfile function 
                                 //and this countinues untill we reach a file which has
                                 //no sub directories
    
            }
        }
        return path;// returning path variable as it is the return type and also 
                    // because function needs path as argument.
    
        }   
    }
    
    0 讨论(0)
  • 2020-11-29 05:35

    I have used a different approach to search for a file using stack.. keeping in mind that there could be folders inside a folder. Though its not faster than windows search(and I was not expecting that though) but it definitely gives out correct result. Please modify the code as you wish to. This code was originally made to extract the file path of certain file extension :). Feel free to optimize.

    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @author Deepankar Sinha
     */
    public class GetList {
        public List<String> stack;
        static List<String> lnkFile;
        static List<String> progName;
    
        int index=-1;
        public static void main(String args[]) throws IOException
        {
    
            //var-- progFile:Location of the file to be search. 
            String progFile="C:\\";
            GetList obj=new GetList();
            String temp=progFile;
            int i;
            while(!"&%@#".equals(temp))
            {
                File dir=new File(temp);
                String[] directory=dir.list();
                if(directory!=null){
                for(String name: directory)
                {
                    if(new File(temp+name).isDirectory())
                        obj.push(temp+name+"\\");
                    else
                        if(new File(temp+name).isFile())
                        {
                            try{
                                //".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
                            if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
                            {
                                //obj.addFile(temp+name,name);
                                System.out.println(temp+name);
                            }
                            }catch(StringIndexOutOfBoundsException e)
                            {
                                //debug purpose
                                System.out.println("ERROR******"+temp+name);
                            }
    
                        }
                }}
                temp=obj.pop();
            }
            obj.display();
    
    //        for(int i=0;i<directory.length;i++)
    //        System.out.println(directory[i]);
        }
    
        public GetList() {
            this.stack = new ArrayList<>();
            this.lnkFile=new ArrayList<>();
            this.progName=new ArrayList<>();
        }
        public void push(String dir)
        {
            index++;
            //System.out.println("PUSH : "+dir+" "+index);
            this.stack.add(index,dir);
    
        }
        public String pop()
        {
            String dir="";
            if(index==-1)
                return "&%@#";
            else
            {
                dir=this.stack.get(index);
                //System.out.println("POP : "+dir+" "+index);
                index--;
    
            }
            return dir;
        }
    
        public void addFile(String name,String name2)
        {
            lnkFile.add(name);
            progName.add(name2);
        }
    
        public void display()
        {
            GetList.lnkFile.stream().forEach((lnkFile1) -> {
                System.out.println(lnkFile1);
            });
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 05:42

    This looks like a homework question, so I'll just give you a few pointers:

    Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.

    You're not using Scanner for anything, and it's not needed here, get rid of it.

    Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0; may return true or false, depending on the value of a. But return fileName; will just return the value of fileName, which is a String.

    0 讨论(0)
提交回复
热议问题