Answer the question
In order to leave comments, you need to log in
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.
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);
}
}
}
/** Функция поиска файлов в каталогах
* @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
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
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 questionAsk a Question
731 491 924 answers to any question