使用Java.io.file,可以使用一种方法找到子目录,但不能使用另一种方法

o0lyfsai  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(102)

在我的学校作业中,我们的任务是使用线程来加速文件搜索算法。他们给我们的原始程序是这样的:

package filefinder;

import java.io.File;
import java.io.IOException;

public class FileFinder {
    private final File rootDir;

    public FileFinder(String root) throws IOException {
        rootDir = new File(root);
        if (!(rootDir.exists() && rootDir.isDirectory())) {
            throw new IOException(root + " is not a directory");
        }
    }

    public void findFile(String file) {
        find(rootDir, file);
    }

    private void find(File rootDir, String fileName) {
        File[] files = rootDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.getName().equals(fileName)) {
                    System.out.println("Found at: " + file.getAbsolutePath());
                } else if (file.isDirectory()) {
                    find(file, fileName);
                }
            }
        }
    }
}

它在主文件中被调用:

package filefinder;

import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        try {
            String goal = "needle.txt";
            String root = "haystack";
            FileFinder ff = new FileFinder(root);
            ff.findFile(goal);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这将查找文件。然后,为了使用线程运行它,我尝试将它拆分为5个线程,5个子目录中的每个一个线程。

package filefinder;

import java.io.IOException;
import java.io.File;

public class Main {

    public static void main(String[] args) {
        try {
            String goal = "needle.txt";
            String root = "haystack";
            File file = new File(root);
            File[] children = file.listFiles();
            System.out.println(children);
            for (File child : children)
            {
                if (child.isDirectory()){
                    new FileFinder(child.getName());}
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

然而现在,它抛出了异常“haystack1不是目录”。为什么它不能这样找到子目录?谢谢你。
我确实设法用线程运行它,但它根本没有提高性能。我的一个同学说,这是因为我在for循环的每次迭代中定义了一个新线程,这就是为什么我在这里尝试为每个直接子目录创建一个新线程,所以主文件夹内的5个文件夹。
我们正在搜索的文件夹被称为'haystack',包含5个文件夹,称为'heystack1'到'heystack5',每个文件夹都有相同的5个文件夹,直到某个时间点。

kqlmhetl

kqlmhetl1#

这是因为您只将文件名传递给 FileFinder
从技术上讲,它只是路径中的最后一个元素。
你需要通过整个路径。
您可以使用 File#getPath 作为相对路径,使用 File#getAbsolutePath 作为绝对路径。
类似地,您可以使用 File#getAbsoluteFile 将值作为 File 对象返回。

new FileFinder(child.getAbsolutePath());
new FileFinder(child.getPath());

相关问题