如何导入 Java 中的目录(和子目录)列表?

发布于 2024-07-23 01:17:57 字数 568 浏览 2 评论 0原文

这是我到目前为止的代码:

import java.io.*;

class JAVAFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".java"));
    }
}

public class tester {
   public static void main(String args[])
   {
        FilenameFilter filter = new JAVAFilter();
        File directory = new File("C:\\1.3\\");
        String filename[] = directory.list(filter);
   }
}

此时,它将在字符串数组 filename 中存储目录 C:\1.3\ 中的所有 *.java 文件的列表。 但是,我想将所有 java 文件的列表也存储在子目录中(最好还指定 C:\1.3\ 中的路径。我该如何执行此操作?谢谢!

Here is the code I have thus far:

import java.io.*;

class JAVAFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".java"));
    }
}

public class tester {
   public static void main(String args[])
   {
        FilenameFilter filter = new JAVAFilter();
        File directory = new File("C:\\1.3\\");
        String filename[] = directory.list(filter);
   }
}

At this point, it'll store a list of all the *.java files from the directory C:\1.3\ in the string array filename. However, i'd like to store a list of all the java files also in subdirectories (preferably with their path within C:\1.3\ specified also. How do I go about doing this? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一个人的旅程 2024-07-30 01:17:58

恐怕您无法使用 list(FilenameFilter) 方法来做到这一点。 您必须列出所有文件和目录,然后自己进行过滤。 像这样的东西:

public List<File> getFiles(File dir, FilenameFilter filter) {
    List<File> ret = new ArrayList<File>();
    for (File f : dir.listFiles()) {
        if (f.isDirectory()) {
            ret.addAll(getFiles(f, filter));
        } else if (filter.accept(dir, f.getName())) {
            ret.add(f);
        }
    }
    return ret;
}

I'm afraid you can't do it with the list(FilenameFilter) method. You'll have to list all files and directories, and then do the filtering yourself. Something like this:

public List<File> getFiles(File dir, FilenameFilter filter) {
    List<File> ret = new ArrayList<File>();
    for (File f : dir.listFiles()) {
        if (f.isDirectory()) {
            ret.addAll(getFiles(f, filter));
        } else if (filter.accept(dir, f.getName())) {
            ret.add(f);
        }
    }
    return ret;
}
清醇 2024-07-30 01:17:58

据我所知,您必须手动(递归)执行此操作,即您必须为 C:\1.3\ 的所有子目录调用 list(filter) ,依此类推......

As far as I know, you will have to do this manually (recursively), i.e. you will have to call list(filter) for all sub-directories of C:\1.3\, and so on....

も星光 2024-07-30 01:17:57

你应该查看 DirectoryWalker阿帕奇

you should look at DirectoryWalker from Apache

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文