Java:Jar包运行时如何获取指定资源目录下特定前缀文件名?
资源目录下匹配特定前缀文件的问题
我使用JDK 17和Gradle 7.6开发,项目中img文件夹的所有文件已被包含在构建目录中。现在需要在资源文件夹的特定子目录里,查找文件名以orientation子串开头的文件,获取文件名后用于JavaFX GUI加载图片,但尝试了两种方法均未成功:
使用Reflections的尝试
private static String infoToPath(String info, String orientation) { // [...] 将info转换为roomDir的逻辑 String roomDir = "img/100/108/"; Reflections reflections = new Reflections("com.client", new ResourcesScanner()); Set<String> resourceList = reflections.getResources(Pattern.compile(".*")); String image = resourceList.iterator().next(); return image; }
这段代码抛出NoSuchElementException(说明resourceList为空),但src/main/resources/img/100/108/目录并非空目录,而且正则表达式.*应该能匹配所有内容。
使用InputStream的尝试
private static String infoToPath(String info, String orientation) { // [...] 将info转换为roomDir的逻辑 String roomDir = "img/100/108/"; InputStream resourceStream = GameController.class.getResourceAsStream("roomDir"); File tempFile = null; try { tempFile = File.createTempFile("temp", ".txt"); } catch (IOException e) { throw new RuntimeException(e); } try (OutputStream outputStream = new FileOutputStream(tempFile)) { byte[] buffer = new byte[1024]; int length; while ((length = resourceStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } } catch (IOException e) { throw new RuntimeException(e); } File file = new File(tempFile.getAbsolutePath()); File[] files = file.listFiles(); String name = null; for (File image : files) { if (image.getName().substring(0,1).equals(orientation)) { // 匹配文件名首字符与orientation一致 name = image.getName(); } } tempFile.delete(); return name; }
这个方法始终因为resourceStream为null而失败,我尝试过多种路径字符串,包括:
./src/main/resources/img/100/108/src/main/resources/img/100/108/./img/100/108img/100/108
我知道自己肯定存在错误的假设,但一直找不到问题所在。
内容的提问来源于stack exchange,提问作者Tzatzikiiii
相关产品推荐
相关产品推荐

