gpt4 book ai didi

java - 获取目录中的所有图像 - jar 文件中

转载 作者:行者123 更新时间:2023-11-30 04:42:11 26 4
gpt4 key购买 nike

我的项目中有一个文件夹,其中有 238 张图像。我希望能够找到目录中的所有图像。

我目前正在访问所有这些图像,如下所示:

File directory = new File(FileNameGuesser.class.getResource(DIRECTORY).getPath());
for (File file : directory.listFiles()) {
// filter, process, etc.
}

这在 Eclipse 中工作得很好。但是,当我导出到 jar 文件时,FileNameGuesser.class.getResource(DIRECTORY) 返回 C:\Users\...\file.jar!\org\... code> (因为它是压缩的,我猜)并且该方法中断了。

我怎样才能实现这个目标?

编辑:如果可能的话,我想找到一个既能在 Eclipse 中运行又能在部署的 jar 中运行的解决方案。

最佳答案

实际上不可能以任何好的、干净的方式实现。

如果能够执行 .getClass().getResources("/pictures/*.jpg") (或其他操作),那就太好了,但我们做不到。

你能做的最好的事情就是作一点欺骗。如果您知道存储图像的 jar 文件的名称,则可以使用 JarFileZipFile API 获取列表:

ZipFile zipFile = null;
try {

zipFile = new ZipFile(new File("...")); // Path to your Jar
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {

ZipEntry entry = entries.nextElement();

// Here, I've basically looked for the "pictures" folder in the Zip
// You will need to provide the appropriate value
if (!entry.isDirectory() && entry.getName().startsWith("pictures")) {

// Basically, from here you should have the full name of the
// image. You should be able to then construct a resource path
// to the image to load it...

// URL url = getClass().getResource("/" + entry.getName());
System.out.println(entry.getName());

}

}

} catch (Exception exp) {

exp.printStackTrace();

} finally {


try {
zipFile.close();
} catch (Exception e) {
}

}

如果您事先不知道这些图像的名称,更好的解决方案是不要将这些图像嵌入到您的 jar 中。

您的应用程序确实应该提前知道嵌入式资源的名称。

按照 AndrewThompson 的建议,您可以生成资源列表,并将其添加到您的 Jar 文件中。在运行时,您将加载此文件并有权访问所有资源。

关于java - 获取目录中的所有图像 - jar 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12015747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com