如何在Java中获取没有扩展名的文件?

如何在Java中获取没有扩展名的文件?,java,spring-boot,Java,Spring Boot,我正在将图像保存到我的资源文件夹,而不考虑扩展名,并且我希望以相同的方式加载它们。示例:我想得到名为“foo”的图像,不管它是“foo.jpg”还是“foo.png” 现在,我正在为每个扩展加载映像并返回它(如果它存在),或者在引发异常时尝试下一个扩展,如下所示: StringBuilder relativePath=new StringBuilder().append(“src/main/resources/static/images/”).append(“/”) .append(id).a

我正在将图像保存到我的资源文件夹,而不考虑扩展名,并且我希望以相同的方式加载它们。示例:我想得到名为“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;
试一试{
imageFile=新文件(新的StringBuilder(relativePath).append(“.jpg”).toString());
imageBytes=Files.readAllBytes(imageFile.toPath());
}捕获(IOE异常){
}
如果(imageBytes==null){
imageFile=新文件(relativePath.append(“.png”).toString();
imageBytes=Files.readAllBytes(imageFile.toPath());
}

我觉得这不是最好的方法,有没有办法通过名称加载图像而不考虑扩展名?

您需要检查文件是否存在

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];

请发布一些相关的代码提示:获取文件夹中的文件列表,然后使用子字符串检查文件名是否符合您的条件
if(fileName.equals(“foo”)| | fileName.startsWith(“foo”){…}
,然后您可以正常使用完整路径(原始名称)加载文件。