首页 > 解决方案 > 如何在Java中获取没有扩展名的文件?

问题描述

无论扩展名如何,我都将图像保存到我的资源文件夹中,并且我想以相同的方式加载它们。示例:我想获取名为“foo”的图像,无论它是“foo.jpg”还是“foo.png”。

现在我正在为每个扩展加载图像,如果它存在则返回它,或者如果抛出异常,则尝试下一个扩展,如下所示:


    StringBuilder relativePath = new StringBuilder().append("src/main/resources/static/images/").append("/")
                    .append(id).append("/").append(imageName);
    File imageFile = null;
    byte[] imageBytes = null;
    try {
            imageFile = new File(new StringBuilder(relativePath).append(".jpg").toString());
            imageBytes = Files.readAllBytes(imageFile.toPath());
        } catch (IOException e) {
        }
    if (imageBytes == null) {
            imageFile = new File(relativePath.append(".png").toString());
            imageBytes = Files.readAllBytes(imageFile.toPath());
        }

我觉得这不是最好的方法,有没有办法按名称加载图像而不管扩展名如何?

标签: javaspring-boot

解决方案


您需要检查文件是否存在

File foo = new File("foo.jpg");
if (!foo.exists) {
  foo = new File("foo.png");
}

但是,如果您真的想在不使用扩展名的情况下加载,那么您可以列出目录中与给定模式匹配的文件。

File dir = new File("/path/to/images/dir/");
File [] files = dir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.matches("foo\\.(jpg|png)");
    }
});

File foo = files[0];

推荐阅读