Finding which JAR contains a class – one upping Mark

So my compatriot Mark posted a little utility he just wrote that makes it easy to find out which JAR file contains the file you’re looking for.

I often want to search through a large number of JAR files looking for a particular class, and every time I do this I wish I had some utility to make it easier.

Which inspired me to dust off my only part done equivalent and finish it up. So here’s my version of Mark’s utility. It’s mostly the same – I just added a very simple cache so that you only have to read each jar file once.

#!/bin/sh
TARGET="$1"

CACHEDIR=~/.jarfindcache

# prevent people from hitting Ctrl-C and breaking our cache
trap 'echo "Control-C disabled."' 2

if [ ! -d $CACHEDIR ]; then
    mkdir  $CACHEDIR
fi

for JARFILE in `find $PWD -name "*jar"`
do
  CACHEFILE=$CACHEDIR$JARFILE

  if [ ! -s $CACHEFILE ]; then
      mkdir -p `dirname $CACHEFILE`
      nohup jar tvf $JARFILE > $CACHEFILE
  fi

  grep $TARGET $CACHEFILE > /dev/null
  if [ $? == 0 ]
  then
    echo "$TARGET is in $JARFILE"
  fi
done

 

Thanks for the inspiration Mark!

Update: Mark enhanced the script to automatically update the cache whenever a jar file is changed. Get the updated script from Mark’s blog

Perhaps we should put this and our other clever tools in a public source code repository!

Add Your Comment