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.
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
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
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
.
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
I developed a tool just for this occasion: https://github.com/javalite/jar-explorer
精彩评论