我的项目中有一个文件夹,其中有 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 文件的名称,则可以使用 JarFile
或 ZipFile
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/