indira
indira

Reputation: 83

Searching a file in a jar

I have a directory containing jar file's ,now i want to search a particular file say log4j.xml which is contained in some jar in that directory.I am not getting how to search that file.Please help me out with it.

Upvotes: 0

Views: 2297

Answers (5)

ipolevoy
ipolevoy

Reputation: 5518

I developed a tool just for this occasion: https://github.com/javalite/jar-explorer

Upvotes: 0

Christian Schlichtherle
Christian Schlichtherle

Reputation: 3155

If the JAR is not on the class path, but a regular file in the file system, then you could use TrueZIP 7 to do the job:

First, setup TrueZIP to have the module truezip-driver-zip on the run time class path. Then suit the following code to your particular needs:

TFile jar = new TFile("path/to/my.jar"); // a subclass of java.io.File
if (jar.isDirectory()) // true for regular directories and JARs if truezip-driver-zip is on your run time class path
    for (TFile entry : jar.listFiles()) { // iterate top level directory
        if ("log4j.xml".equals(entry.getName())) {
            // Bingo! Now read the file or write it
            InputStream in = new TFileInputStream(entry);
            try {
                ... // do something here
            } finally {
                in.close();
            }
        } else if (entry.isDirectory()) {
            ... // use recursion to continue searching in this directory
        }
    }

Regards, Christian

Upvotes: 0

laher
laher

Reputation: 9110

If you mean a jar on the classpath, then you can use getResource or getResourceAsStream.

(If not, then see @Bohzo's answer, re: java.util.zip)

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)

I would normally call it as follows:

this.getClass().getClassLoader().getResource("log4j.xml");

Note also the related methods: getResourceAsStream(), getResources, findResources, etc.

HTH

Upvotes: 1

dcn
dcn

Reputation: 4469

with jar tf <filename> you can list the contents of a jar file. If there is a bunch of those you can use something like find . -name "*.jar" -exec jar tf {} \; | grep log4j.xml

Upvotes: 1

Bozho
Bozho

Reputation: 597402

It very much depends on one thing - is your jar on the classpath or not.

  • if it is not on the classpath, you will have to open it as a zip archive (with java.util.zip or commons-compress) and browse for the specific entry
  • if it is on the classpath, you can use a resource framework like the one in spring, where you can specify classpath:log4j.xml.

Upvotes: 0

Related Questions