FileFinder using Breadth First Search algorithm fails

  • Java
  • Thread starter Sam Groves
  • Start date
  • #1
Sam Groves
11
0
I am developing a app which would be like the File Explorer except the fact that it will have many more features to it.

I am trying to implement a function
Code:
 void calc()
which would try to find a file with a specific relative path.I am using the Breadth First Search algorithm for my blind search.

I have this Java Class:

FileFinder:
import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
public class FileFinder
{
  String searchPath;
  String diskLocation;
  String[]locations;
  public FileFinder(String searchPath,String diskLocation)
  {
    this.searchPath = searchPath;//specificy search path
    this.diskLocation = diskLocation;//specify disk location
    locations = new String[33];
  }

  public void calc() throws IOException {
    int x = 0;
    ArrayDeque<String>searchedFiles = new ArrayDeque<>();
    searchedFiles.add(diskLocation);
    while(!searchedFiles.isEmpty())//if queue is empty we have carried out our search
    {
      for(String i:searchedFiles)
      {
        System.out.println(i);
        File f = new File(i);
          try{
            var files = f.listFiles();//if the java file is a directory
            while(files!=null) {
              for (File fl : files) {
                searchedFiles.addLast(fl.getCanonicalPath());//add every Java file of the directory to the queue
              }
            }
          }
          catch(Exception e)
          {
          }
          if(f.isFile())if the Java file is a file
        {
          if(f.getPath()==searchPath)if relative path -> search path
          {
            if(x< locations.length-1)check if there is space in the array to not overwrite strings/be out of bounds
            {
              locations[x] = f.getCanonicalPath();//add canonical path to the array of results
              x++;//increment x
            }
          }
        }
        searchedFiles.remove(i);//remove the visited Java file
      }
    }
printFindings();
  }
public void printFindings()
{
    for(String i:locations)
    {
      System.out.println(i);
    }
}
}

I am inserting my USB Flash Drive which has few directories and files in total(10 or 11?)
But when I call it in main it prints out this message:

Java:
D:\
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.base/java.util.Arrays.copyOf(Arrays.java:3720)
    at java.base/java.util.Arrays.copyOf(Arrays.java:3689)
    at java.base/java.util.ArrayDeque.grow(ArrayDeque.java:150)
    at java.base/java.util.ArrayDeque.addLast(ArrayDeque.java:308)
    at FileFinder.calc(FileFinder.java:54)
    at Main.main(Main.java:11)

The searchPath parameter is HelloWorld.txt , I have created one file at the D:\ directory and one at the D:\as\ directory so I expected the canonical paths of those 2 files to be shown in the output however I get this weird message.

As you see D:\ is printed out correctly but then why it throws a OutOfMemory exception?I suspect there is a endless loop but cant seem to figure out where it is.
 
Technology news on Phys.org
  • #2
My suggestion would be to use a debugger and step through the code as it executes.

Alternatively, you could print the isEmpty flag set as you loop and print out when you add or drop an entry. It should become obvious where you went wrong.

one possible trip up could be searching over a dot or double dot directory Ie
”,” is the current directory and “..” is the parent directory.
 
  • #3
In addition to what @jedishrfu said about using a debugger, you should come up with a better name for the function you're trying to write.
Sam Groves said:
I am trying to implement a function void calc() which would try to find a file with a specific relative path.
Coming up with a better name would help readers (including yourself in a few weeks) understand what the function is supposed to do. Your description of what this function should do might give you an idea for a better name.
 
  • Like
Likes jedishrfu

1. Why does my FileFinder using Breadth First Search (BFS) not find a file that exists?

This issue could be due to several reasons. First, ensure that the starting directory in your BFS algorithm is correct and includes the path where the file is located. Additionally, check if your BFS algorithm correctly explores all directories without prematurely terminating. File permissions issues might also prevent the BFS from accessing certain directories or files, so verify the permissions are correctly set.

2. Why is the BFS-based FileFinder slow?

The performance of a BFS-based FileFinder can be slow if the directory structure is large and deep because BFS explores all nodes at the present depth level before moving on to nodes at the next depth level. This can lead to significant overhead when traversing large, deeply nested directories. Optimizing the way directories are queued and de-queued, or using a heuristic to skip certain paths, might improve performance.

3. How can I handle symbolic links to avoid infinite loops in BFS FileFinder?

Symbolic links can create cycles in the filesystem, which may cause an infinite loop in a BFS algorithm. To handle this, you can maintain a set of visited directories. Before traversing into a directory, check if it's already in the set of visited directories. If it is, skip it; otherwise, add it to the set and continue. This ensures each directory is processed only once.

4. What should I do if the BFS FileFinder throws a permission error?

If your BFS FileFinder encounters a permission error, you have a few options. You can catch these errors and skip the inaccessible directories or files, logging the issue for later review. Alternatively, you can run the FileFinder with higher privileges, although this approach should be used cautiously due to potential security risks. Always ensure that your application adheres to the principle of least privilege.

5. How can I modify the BFS algorithm to search for multiple files at once?

To adapt a BFS algorithm for searching multiple files simultaneously, you can maintain a list of target files instead of a single filename. As each directory is explored, check all files in that directory against the list of target files. When a match is found, you can record the result and continue searching for other files. This approach allows you to efficiently find multiple files in one pass through the filesystem.

Similar threads

  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
4
Views
3K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
3
Replies
75
Views
4K
  • Programming and Computer Science
Replies
1
Views
751
  • Programming and Computer Science
Replies
28
Views
3K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
Back
Top