在项目的源文件夹中查找某个扩展名的所有文件

Finding all the files of a certain extension in a project's source folder

您好,我正在尝试从源文件夹(下方)

中检索类型为 .mp3 的所有文件的名称

下面是我用来区分文件类型并添加到列表中的代码。但是我不知道我应该在 directory 中输入哪个参数它应该是 music 文件夹但是我不知道如何表示这个。

    File dir = new File("");
    String[] files = dir.list(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".mp3");
        };
    });
    for(int a = 0; a < files.length; a++)
    {
        musicList.add(files[a]);
    }

如果您使用的是 Servlet:

ServletActionContext.getServletContext().getRealPath("music"); 

如果使用 Spring:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("music").getFile());
System.out.println(file.getAbsolutePath());

对于 javafx,请参见:

How to target a file (a path to it) in Java/JavaFX

试试这个。

List<String> result = Files.find(Paths.get("music"), 100,
    (p, a) -> p.toString().toLowerCase().endsWith(".mp3"))
    .map(path -> path.toString())
    .collect(Collectors.toList());