如何检查JAR中是否存在JAR文件和特定文件?

yeg*_*256 14 java

假设文件名在此URL中:

URL file = new URL("jar:file:/path/to/foo.jar!/META-INF/file.txt");
Run Code Online (Sandbox Code Playgroud)

IOException如果现有jar中没有foo.jar或没有file.txt内部,则此操作会导致:

import org.apache.commons.io.FileUtils;
FileUtils.copyURLToFile(file, /* some other file */);
Run Code Online (Sandbox Code Playgroud)

是否可以验证文件存在而无异常捕获?

Gre*_*reg 12

您可以使用java.util.jar.JarFile类,并使用getJarEntry方法查看该文件是否存在.

JarFile jar = new JarFile("foo.jar");
JarEntry entry = jar.getJarEntry("META-INF/file.txt");
if (entry != null) {
    // META-INF/file.txt exists in foo.jar
}
Run Code Online (Sandbox Code Playgroud)