【问题标题】:Reading From directories+sub-directories从目录+子目录读取
【发布时间】:2012-11-25 05:11:49
【问题描述】:

这是一个半功课,我已经尝试了很长时间但没有运气,基本上我正在做一个类似搜索引擎的程序,我在我的目录中读取文件+他们的子目录并读取文本文件进行搜索对于一场比赛,我无休止地搜索但没有明确的答案,所以如果有人能提供帮助,我将不胜感激。

这是我最好的尝试,但它的问题是它只从子目录中获取文件而忽略了主/根目录,试图找出原因但不能。

 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 ");

   }}

搜索网络并尝试模仿我发现的内容后的第二个版本,但遗憾的是没有工作。

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 ");

   }}

【问题讨论】:

    标签: java directory subdirectory


    【解决方案1】:

    在第一个版本中,您循环遍历整个 file.length 并仅检查 file.isDirectory,然后(即在遍历所有文件/文件夹之后)检查它是否是一个文件。这就是为什么您无法读取当前目录的文件的原因。简单地说

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

    阻塞在 for 循环中,它应该在第一个版本中工作。 还有一件事我不明白这里 ls 变量的用途。

    【讨论】:

    • if(files[i].isFile())) 已经在 For 循环中,对不起,如果括号混淆了。[ls] 基本上是一个链表数组,它没有任何用途在这种方法中,但重要的是存储每个链接列表的地址,我在其中保存了单词以在搜索方法(索引)中使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2020-04-10
    • 2021-08-07
    相关资源
    最近更新 更多