file.getFileName().endsWith()没有检测到.mp3

jel*_*mew 2 java

我可能错过了一些小东西,但我找不到它.使用file.getFileName().endsWith(".mp3"),布尔值始终为false.如果我将te文件重命名为*.mp并将代码更改为endsWith(".mp"),则会找到它们.这里发生了什么?

问候,Jelmew

编辑:文件是一个路径对象顺便说一句.

文件名:

/home/jelmer/Music/01 - Nightwish - Shudder Before The Beautiful.mp3
/home/jelmer/Music/02 - Nightwish - Weak Fantasy.mp3
/home/jelmer/Music/03 - Elan (Album Version).mp3
/home/jelmer/Music/04- Nightwish - Yours Is An Empty Hope.mp3
/home/jelmer/Music/05 - Nightwish - Our Decades In The Sun.mp3
/home/jelmer/Music/06 - Nightwish - My Walden.mp3
/home/jelmer/Music/07 - Nightwish - Endless Forms Most Beautiful.mp3
/home/jelmer/Music/08 - Nightwish - Edema Ruh.mp3
/home/jelmer/Music/09 - Nightwish - Alpenglow.mp3
/home/jelmer/Music/10 - Nightwish - Eyes Of Sharbat Gula.mp3
/home/jelmer/Music/11 - Nightwish - The Greatest Show on Earth.mp3
/home/jelmer/Music/test.mp3


public class mp3Walker extends SimpleFileVisitor<Path> {

    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        if(file.getFileName().endsWith(".mp3")) {
            System.out.println(file);
        }
        System.out.println("done with file: "+file.getFileName());
        return FileVisitResult.CONTINUE;
    }

    public static void main(String[] args) throws IOException {
        mp3Walker walker= new mp3Walker();
        Files.walkFileTree(Paths.get("/home/jelmer/Music/"), walker);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

done with file: 07 - Nightwish - Endless Forms Most Beautiful.mp3
done with file: test.mp3
done with file: 08 - Nightwish - Edema Ruh.mp3
done with file: 05 - Nightwish - Our Decades In The Sun.mp3
done with file: 02 - Nightwish - Weak Fantasy.mp3
done with file: 11 - Nightwish - The Greatest Show on Earth.mp3
done with file: 01 - Nightwish - Shudder Before The Beautiful.mp3
done with file: 10 - Nightwish - Eyes Of Sharbat Gula.mp3
done with file: 04- Nightwish - Yours Is An Empty Hope.mp3
done with file: 06 - Nightwish - My Walden.mp3
done with file: 03 - Elan (Album Version).mp3
done with file: 09 - Nightwish - Alpenglow.mp3
Run Code Online (Sandbox Code Playgroud)

fge*_*fge 12

这是因为Path.endsWith()需要一个完整的路径元素.

那是:

Paths.get("foo").endsWith("oo")
Run Code Online (Sandbox Code Playgroud)

相当于:

Paths.get("foo").endsWith(Paths.get("oo"))
Run Code Online (Sandbox Code Playgroud)

总是返回false.

您想测试文件名的字符串值:

path.getFileName().toString().endsWith(".mp3")
Run Code Online (Sandbox Code Playgroud)