如何在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());
}

我觉得这不是最好的方法,有没有一种方法可以按图像的名称加载图像,而不考虑扩展名?

您需要检查文件是否存在

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

最新更新