简体   繁体   English

从目录+子目录中读取

[英]Reading From directories+sub-directories

this is a semi homework and I've been trying for ages but without luck,basically I'm doing a Search engine-Like program,where i read files in my directory + their sub directory's and Read the text files to search for a match,i searched endlessly but without clear answer so I'd appreciate if any one could help. 这是一个半作业,我已经尝试了很长时间了,但是没有运气,基本上我正在做一个类似于搜索引擎的程序,在该程序中,我读取目录中的文件及其子目录,然后读取文本文件以查找匹配项,我无休止地搜索,但没有明确的答案,因此,如果有任何帮助,我将不胜感激。

this was my best try but the problem with it that it only took the files from the sub directory and ignored the main/root directory,tried to figure out why but couldn't. 这是我的最佳尝试,但问题是它仅从子目录中提取文件,而忽略了main / root目录,试图找出原因,但不能。

 public void indexDirectory(File dir) {
       for(int i=0;i<50;i++)
           ls[i]=new LinkList();//array of Linked lists to store addresses of each Linked list that has a file 
    try{
       files= dir.listFiles();

       for (int i = 0; i < files.length; i++) {
           if(files[i].isDirectory())
               indexDirectory(files[i]);

           if(files[i].isFile()){
               if(files[i]!=null)
                   indexFile(files[i]);
       } //end if(isFile)
      } //end For loop
   }catch(FileNotFoundException e){
       System.out.println("error ");

   }}

second version after serching the web and trying to emulate what i found,but didn't work sadly. 在浏览网络并尝试模仿我发现的内容之后的第二个版本,但并没有令人遗憾地工作。

public void indexDirectory(File dir) {


       for(int i=0;i<50;i++)
           ls[i]=new LinkList();
    try{
       if(dir.isFile()){
     indexFile(dir); //this method takes each directory and read the words and save them  in
                            //      array of linked list
       }
 else if(dir.isDirectory()){
     files= dir.listFiles();
       if(files!=null) {
       for (int i = 0; i < files.length; i++)  {
           if(files[i].isDirectory()){
           indexDirectory(files[i]);      //recursive call
       }}
   }catch(FileNotFoundException e){
       System.out.println("error ");

   }}

In the first version, you loop through the entire file.length and check only for file.isDirectory and after that (ie. after all files/folders have been traversed) you check if it is a file. 在第一个版本中,您遍历整个file.length并仅检查file.isDirectory,然后(即在遍历所有文件/文件夹之后)检查它是否是文件。 That's why you cannot read through current directory's files. 这就是为什么您无法读取当前目录的文件的原因。 Simply put the 简单地把

if(files[i].isFile()){
           if(files[i]!=null)
 indexFile(files[i]);      //the method to read from these files and save to array of lists.
       }

block in for loop and it should work in the first version. 阻止for循环,并且应该在第一个版本中运行。 One more thing I didn't understand the purpose of ls variable here. 还有一件我不了解ls变量的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM