Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check existence of a JAR file and a specific file inside JAR?

Tags:

java

Assume the file name is in this URL:

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

This operation leads to IOException if there is no foo.jar or there is no file.txt inside the existing jar:

import org.apache.commons.io.FileUtils;
FileUtils.copyURLToFile(file, /* some other file */);

Is it possible to validate file existence without exception catching?

like image 875
yegor256 Avatar asked Mar 14 '11 18:03

yegor256


People also ask

How do I access files inside a jar?

You can use getResource() to obtain a URL for a file on the classpath, or getResourceAsStream() to get an InputStream instead. Show activity on this post. You could read the contents of a JAR file using the JarFile class.

How do I search for a specific JAR file in Linux?

To find the . jar files that contain a class, you can use the FindClass.sh script. First go to a UNIX installation of Sterling Platform/MCF. If the FindClass.sh script already exists it should be in your $YFS_HOME directory or your $YFS_HOME/lib directory.

How do you find out which JAR file an import comes from?

Right-click anywhere in the source window and select "Select In Projects". The class will show highlighted in the jar where it came from.


1 Answers

You can use the java.util.jar.JarFile class, and use the getJarEntry method to see if the file exists.

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
}
like image 123
Greg Avatar answered Oct 13 '22 21:10

Greg