N
N
NameOf Var2017-03-18 18:59:57
Java
NameOf Var, 2017-03-18 18:59:57

What is wrong with the search algorithm?

I wanted to implement a file search algorithm to find all matches:
All matches will be output to the find variable of ArrayList type. Below is the algorithm itself.

spoiler
package com.filefind;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Find {
    public static void main(String args[]) {
        long start = System.currentTimeMillis();
        try {

            ArrayList<File> find = new ArrayList<>(200);
            findFile("D:\\Autodesk", find, "README");
                find.forEach(System.out::println);
        }
        catch (NullPointerException error) {
            System.out.println("File not found!");
        }
        long end = System.currentTimeMillis();
        System.out.println("Поиск занял: " + (double) (end - start) / 1000 + " секунд");
    }

    public static void findFile(String path, List<File> result, String name) {
        if (!path.endsWith("\\"))
            path += "\\";
        File list[] = (new File(path)).listFiles();
        for (File file : list) {
            if (file.getName().contains(name))
                result.add(file);
            if (file.isDirectory())
                findFile(path + file.getName() + "\\", result, name);
        }
    }
}

There are n files on the D:\ drive. If you drive in a specific folder on this drive (ie D:\Folder1\), then the search works quickly and gives the correct result. If the path argument is set to D:\, then the search is performed for 5-10 seconds and a NullPointerException is thrown, however, all files and folders on the D:\ drive are run through. A search through Windows Explorer showed that 80 files containing the text README are stored on the disk. Why is null stored in the find variable after the run?
upd: Solved the problem. File search algorithm code:
spoiler
/** Функция поиска файлов в каталогах
     * @param path - путь, в котором следует выполнить поиск
     * @param result - в списке result будут храниться все совпадения
     * @param name - имя файла, которое следует найти
     */
    private static void findFile(String path, List<File> result, String name) {
        if (!path.endsWith("\\"))
            path += "\\";
        File list[] = (new File(path)).listFiles();
        if (list == null) return; // если listFiles() возвращает null, значит не удалось прочитать текущую папку (ограничение доступа в системе)
        for (File file : list) {
            if (file.getName().toLowerCase().contains(name.toLowerCase()))
                result.add(file);
            if (file.isDirectory())
                findFile(path + file.getName() + "\\", result, name);
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene Khrustalev, 2017-03-18
@eugenehr

What's in the list[] variable for D:\?
PS: Path separator in Java is cross-platform and regardless of the OS, you should use '/'
Also, in order not to track these slashes when concatenating file names, it's better to use the File(File, String) constructor

N
NameOf Var, 2017-03-18
@hax

I think I have found the cause of the error. I have one hidden folder on my D:\ drive, access to which is restricted by the system. That is why when trying to read this folder, an exception takes off. Now the question is: how do I programmatically catch folders that are restricted? Use try..catch or is there another way to implement it?
upd: Solved the problem. For some reason, the canExecute() method did not help, but I noticed that if the listFiles() method passes null, then reading this folder is impossible, so we just exit the method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question