java - 如何在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];
推荐阅读
- c++ - 如何使用 pthreads 以正确的方式设置两个线程之一的优先级
- php - 使用PHP发送邮件未在收件箱中显示所有填写的表格
- android - 如何向服务器发布任何内容但没有使其为空
- python - 如何在python的多行字符串中使用具有不同模式的正则表达式
- mongodb - Elasticsearch MongoDB 集成工具建议
- asp.net-mvc - 如何在 ASP.NET MVC 应用程序中对“Azure AD 和 OpenID Connect”代码进行单元测试
- sql-server - 使用 SimpleJdbcCall 优化 MSSQL 服务器中存储过程的执行
- python - 为什么 tf.train.import_meta_graph 非常非常慢?
- css - 删除移动视图上的 CSS 底部属性
- javascript - 如何在 btn-edit 上使用 cick 从 contentNote 中删除类显示并将类显示添加到 txtAreaNote?