Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: JarInputStream

  1. #1
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default JarInputStream

    I'm confused with the JarInputStream class.

    JarInputStream takes in an InputStream, but an InputStream of what? Is it the Jar file as an InputStream? It cant be the files inside as an InputStream because isnt that what getNextEntry() and getNextJarEntry() methods are for?

    If it is supposed to be an InputStream of the Jar, how the heck to I get that? Specifically, I am trying to get the InputStream of the Jar that is being executed to run the program so I can get particular JarEntries inside of it.

    I could use some quick help. Any information is appreciated.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: JarInputStream

    I am trying to get the InputStream of the Jar that is being executed to run the program
    Not sure what you are asking. You don't execute a jar, you execute a class file that is in a jar.
    There isn't an InputStream for the jar (well maybe in the classloader that is reading the class files from the jar).

    To get the file path to the jar file that your class file is in, look at the the getResource method.
    Here's a program I wrote long ago that does some of that:
    // Get folder that a class was loaded from
    /*  Changes
       7/28/05 - Added pathToJar
       8/18/05 - Added leading / for Mac
       9/26/06 - Added URLDecoder
       5/16/08 - Added Linux code
    */
     
    package NormsTools;
     
    import java.net.URL;
    import java.io.File;
    import java.util.zip.*;
    import java.util.Date;
    import java.net.URLDecoder;
     
     
    public final class FindOurHome {
     
       final public static String Version = "FindOurHome 16 May 2008";
     
       final static boolean    debug = false;     // For debug output
     
     
       private static boolean  setHomeLoc = false;
       private static boolean  homeLocInJar = false;  // true if class file from jar
     
       private static String  URLStr = "";
       private static String  pathToJar = null;
     
        // Here are the possible headers and id strings (see below):
        private final static String JAVA_HDR1 = "file:/";
        private final static String JAVA_HDR2 = "jar:";
        private final static String JAVA_SEP = "!";
        private final static String Percent = "%";
        private final static String JVIEW_HDR1 = "systemresource:/FILE";
        private final static String JVIEW_HDR2 = "systemresource:/ZIP";
        private final static String JVIEW_SEP1 = "/+/";
        private final static String JAR_EXT = ".jar";
        private final static String   MetaFILE = "META-INF/MANIFEST.MF";  
        private final static String OS_Win = "Win";
        private final static String OS_Mac = "Mac";
        private final static String OS_Linux = "Linux";
     
       //-------------------------------------------------------------------
       public final static String getHomeLoc(Object obj, String className) {
           if(debug) {
             System.out.println("FOH.getHomeLoc(): class is " + obj.getClass());
           }
           URL ourLoc = obj.getClass().getResource(className);
           if (ourLoc == null) {
             System.err.println("FOH.getHomeLoc(): getResource returned null for " 
                                     + className + " with " + obj);
             return "";
           }
           if (debug)
             System.out.println("FOH.Loaded from=" + ourLoc
                           + ",\n    getProtocol()=" + ourLoc.getProtocol()
                           + ",\n    getHost()=" + ourLoc.getHost() 
                           + ",\n    getFile()=" + ourLoc.getFile());
     
       //   Output when from a class file:
       //JAVA >Loaded from  file:/D:/JavaDevelopment/SlideShow/ImgIdxEditor.class,
       //               getFile=/D:/JavaDevelopment/SlideShow/ImgIdxEditor.class
       //JVIEW>Loaded from  systemresource:/FILED:\JavaDevelopment\SlideShow\/+/ImgIdxEditor.class,
       //               getFile=/FILED:\JavaDevelopment\SlideShow\/+/ImgIdxEditor.class
     
       //   Output when load from a jar:
       //JAVA >Loaded from  jar:file:/C:/My_Photos/SlideShowApp.jar!/ImgIdxEditor.class,
       //               getFile=file:/C:/My_Photos/SlideShowApp.jar!/ImgIdxEditor.class
       //JVIEW>Loaded from  systemresource:/ZIPC:\My_Photos\SlideShowApp.jar/+/ImgIdxEditor.class,
       //               getFile=/ZIPC:\My_Photos\SlideShowApp.jar/+/ImgIdxEditor.class
       //JDK118>Loaded from=systemresource:/ZIP1/+/NormsTools/FindOurHome.class,
       //               getFile=/ZIP1/+/NormsTools/FindOurHome.class
     
       // Linux: URLStr=jar:file:/home/norm/www/HTTPServer.jar!/HTTPServer/httpd.class
     
       // On Mac: this pgm returned: 6/+/SlideShow/  when jar was in the folder: <?>SlideShow
     
           URLStr = ourLoc.toString();
           if(URLStr.indexOf(Percent) >= 0) {
             try {
                URLStr = URLDecoder.decode(URLStr, "UTF8");   // Doesn't work???
                System.out.println("decode= " + URLStr);
             }catch(Exception ex) {
                ex.printStackTrace();
                return "";
             }
           }
           String propFolder = "";
     
           int ix, iy;
     
           homeLocInJar = false;           // Reset
           setHomeLoc = true;
           String os = System.getProperty("os.name");
           if(!os.startsWith(OS_Win) && !os.startsWith(OS_Mac) && !os.startsWith(OS_Linux)) {
             System.err.println("Unknown OS - " + os);
           }
     
           //  Parse depending on Java or JVIEW
           if (URLStr.startsWith(JVIEW_HDR1)) {
             // From a class file
             ix = URLStr.indexOf(JVIEW_SEP1); // Get end of filename
             propFolder = URLStr.substring(JVIEW_HDR1.length(), ix);
     
           }else if (URLStr.startsWith(JVIEW_HDR2)) {
             // From a jar file - get drive thru last /
             ix = URLStr.lastIndexOf(File.separator);
             if (ix > JVIEW_HDR2.length()) {
                propFolder = URLStr.substring(JVIEW_HDR2.length(), ix+1);
                homeLocInJar = true;
             } else {
                System.err.println("FOH.getHomeLoc(): Unknown format1: " + URLStr);
             }
     
           }else if ((iy = URLStr.indexOf(JAVA_HDR1)) >= 0) {
             // Its Java program
             if (URLStr.startsWith(JAVA_HDR2)) { // in a jar?
                // Its in a jar file
                ix = URLStr.indexOf(JAVA_SEP);  // set ptr to end of path to jar
                homeLocInJar = true;
     
             }else {
                ix = URLStr.length();
             }
     
             int iz = URLStr.lastIndexOf("/", ix); // Get sep that's before the jar fn
             if (iz > JAVA_HDR1.length()) {
                propFolder = URLStr.substring(iy 
                   + JAVA_HDR1.length(), iz+1).replace('/', File.separatorChar);
                pathToJar = URLStr.substring(iy 
                   + JAVA_HDR1.length(), ix).replace('/', File.separatorChar);
             }else {
                System.err.println("FOH.getHomeLoc(): Unknown format2: " + URLStr);
             }
             if(os.startsWith(OS_Mac)) {   // Quick and dirty code?????
                // Need leading / on Mac
                propFolder = File.separator + propFolder;
                pathToJar = File.separator + pathToJar;
             }else if(os.startsWith(OS_Linux)) {
    //            System.out.println("FindOurHome: URLStr=" + URLStr);
                propFolder = File.separator + propFolder;
             }
     
           }else {
             // Unknown program???
             System.err.println("FOH.getHomeLoc(): Unknown format3: " + URLStr);
           }
           if (debug)
              System.out.println("FOH.getHomeLoc(): FilePath=" + propFolder);
     
           return propFolder;
    	 } // end getHomeLoc()
     
        //---------------------------------------------------------------
        public static String getPathToJar(Object obj, String className) {
          getHomeLoc(obj, className);
          if(homeLocInJar)
             return pathToJar;
          else
             return null;
        } // end getPathToJar()
        //---------------------------------------------------------
        // Was class file in a jar?
        public static boolean fromJar() {
          if (!setHomeLoc)
             throw new RuntimeException("Must call getHomeLoc() first");
          return homeLocInJar;
        }
     
        final static long NO_DATE = 0L;    // When no valid date found
        //---------------------------------------------------------
        // Get build date of a Jar file. Use the manifest's date!
        // Args: object that was loaded from the jar. Currently NOT USED??? 
        public static long getBuildDate(Object obj) {
          if (!fromJar() || URLStr.indexOf(JAR_EXT) < 0) {
             System.err.println("getBuildDate(): Class was not loaded from a jar");
             return NO_DATE;
          }
          //Parse out the path to the jar file
          int ixJar = URLStr.indexOf(JAR_EXT);
          int lenHdr = JAVA_HDR1.length() + JAVA_HDR2.length(); // Assume java
          if (URLStr.startsWith(JVIEW_HDR2)) {
             lenHdr = JVIEW_HDR2.length();
          }
          if (ixJar < lenHdr) {
             return NO_DATE;
          }
          String jarFN = URLStr.substring(lenHdr, ixJar+JAR_EXT.length());
          try {
             ZipFile zipF = new ZipFile(jarFN);
             ZipEntry ze = zipF.getEntry(MetaFILE);
             if (ze == null) {
                System.err.println("getBuildDate(): Manifest file not found in jar.");
                return NO_DATE;
             }
             long time = ze.getTime();
             zipF.close();
             return time;                  // Return the entry's time
     
          }catch(Exception ex) {
             ex.printStackTrace();
          }
          return NO_DATE;                  // if problem
        } // end getBuildDate()
     
        //----------------------------------------------------------------
        // Following for testing. Comment out when done
    /*    public static void main(String[] args) {
          if (args.length == 0) {
             // Default
             args = new String[]{"FindOurHome.class"};
          }
    //      FindOurHome.debug = true;
          FindOurHome foh = new FindOurHome(); // need an object
          String theFN = FindOurHome.getHomeLoc(foh, args[0]);
          File theFile = new File(theFN);
          System.out.println(args[0] + " loaded from " 
                            + theFile + ", exists?" + theFile.exists() 
                            + ", in jar? " + FindOurHome.fromJar());
          System.out.println("Build date: " + new Date(FindOurHome.getBuildDate(foh)));
     
          // Now test what can be done with the raw URL
          try {
             URL ourLoc = foh.getClass().getResource(args[0]);
             String fn = ourLoc.getFile();
             File tf = new File(fn);
             System.out.println("\nfile=" + fn +", exists? " + tf.exists() + ", size=" + tf.length());
             ZipFile zf = new ZipFile(fn);
             java.util.Enumeration en = zf.entries();
             System.out.println("en has " + en.hasMoreElements());
          }catch(Exception ex) {
             System.out.println(ex);
          }
        } // end main */
    } // end class
     
    /*  Output when run from a jar >>>>>>>
     
    D:\JavaDevelopment\NormsTools\Testing>java.exe -jar FindOurHome.jar
    getHomeLoc(): class is class NormsTools.FindOurHome
    Loaded from=jar:file:/D:/JavaDevelopment/NormsTools/Testing/FindOurHome.jar!/NormsTools/FindOurHome.class,
        getProtocol()=jar,
        getHost()=,
        getFile()=file:/D:/JavaDevelopment/NormsTools/Testing/FindOurHome.jar!/NormsTools/FindOurHome.class
    getHomeLoc(): FilePath=D:\JavaDevelopment\NormsTools\Testing\
     
    FindOurHome.class loaded from D:\JavaDevelopment\NormsTools\Testing\, in jar? true
    Build date: Thu Aug 18 14:42:04 CDT 2005
     
    >>>>>>>>From a class file
    Running: java NormsTools.FindOurHome
     
    getHomeLoc(): class is class NormsTools.FindOurHome
    Loaded from=file:/D:/JavaDevelopment/NormsTools/FindOurHome.class,
        getProtocol()=file,
        getHost()=,
        getFile()=/D:/JavaDevelopment/NormsTools/FindOurHome.class
    getHomeLoc(): FilePath=D:\JavaDevelopment\NormsTools\
     
    FindOurHome.class loaded from D:\JavaDevelopment\NormsTools\, in jar? false
    getBuildDate(): Class was not loaded from a jar
    Build date: Wed Dec 31 18:00:00 CST 1969
     
    file=/D:/JavaDevelopment/NormsTools/FindOurHome.class, exists? true, size=4121
    java.util.zip.ZipException: error in opening zip file
     
    1 error(s)
     
    >>>>>>> From a jar
     
    D:\JavaDevelopment\NormsTools\Testing>java.exe -jar FindOurHome.jar
    getHomeLoc(): class is class NormsTools.FindOurHome
    Loaded from=jar:file:/D:/JavaDevelopment/NormsTools/Testing/FindOurHome.jar!/NormsTools/FindOurHome.class,
        getProtocol()=jar,
        getHost()=,
        getFile()=file:/D:/JavaDevelopment/NormsTools/Testing/FindOurHome.jar!/NormsTools/FindOurHome.class
    getHomeLoc(): FilePath=D:\JavaDevelopment\NormsTools\Testing\
     
    FindOurHome.class loaded from D:\JavaDevelopment\NormsTools\Testing\, in jar? true
    Build date: Thu Aug 18 15:05:58 CDT 2005
     
    file=file:/D:/JavaDevelopment/NormsTools/Testing/FindOurHome.jar!/NormsTools/FindOurHome.class, exists? false, size=0
    java.util.zip.ZipException: The system cannot find the path specified
     
     
    */

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: JarInputStream

    Not sure what you are asking. You don't execute a jar, you execute a class file that is in a jar
    Ok, I meant the I want to access files within the Jar that contains the class that is being executed. I am attempting to access some .class files that will be used to create 3 unique Jars. In order to do that, I believe I need to be able to access those class files as a Stream, as I think that is the only way. From there, I am wanting to grab predetermined class files from the jar is has the class that is being executed and create executable jars with them.

    I'll review the code you posted when I get to work in an hour and I have time to really analyze it.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: JarInputStream

    Ok, I'm completely confused about the whole getResource(String) method. I attempted what you did with the getClass().getResource(args[0]); but I got an index out of bounds exception.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: JarInputStream

    Ok, I actually figured some of this out. Here is the method I made that at least appears to work small-scale, but I can't test it full-scale until I figure out my next problem:
        public void addStream(String source, JarOutputStream target) throws IOException
        {
        	JarEntry t = new JarEntry(source);
    		target.putNextEntry(t);
            BufferedInputStream in = new BufferedInputStream(getClass().getResourceAsStream(source));
            byte[] buffer = new byte[1024];
            while (true)
            {
            	int count = in.read(buffer);
            	if (count == -1)
            		break;
           		target.write(buffer, 0, count);
           	}
            target.closeEntry();
            in.close();
        }

    My next issue is: How can I get a list or something of the .class files in the jar that I am getting my class files from? The reason I need that is because I need to be able to find the unknown amount of .class files that contain the name of: Class$X$X.class where X a random number. For the usual directory, I just used the file.list() method and went through the String[] it returned. But I don't know how to do the same for a .jar or .zip directory. It wouldn't be an issue if I knew every time where the .jar file would be (I could use the JarFile(String) constructor and methods), but it could be located anywhere and that can change.
    Last edited by aussiemcgr; October 11th, 2010 at 03:08 PM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: JarInputStream

    I attempted what you did with the getClass().getResource(args[0]);
    Look at the commented out main method. It shows how to use the class.


    I wrote a project for searching thru the contents of a jar file for entries containing a String. I had a Search program for files in folders and I wanted to use the same code for searching in a jar file without having to change any logic. So I put this together so the search code would think the jar was a folder with subfolders.

    Here's a class that may have some ideas for you:
    // JarTreeElement - Defines objects to hold contents of a jar in a folder hierarchy
    /*  Changes
    *  31 July 2005 - Require both debug switches for Added ... message
        6 Aug  2005 - Added debug info
    */
     
    package NormsTools.InJar;
     
     
    import java.util.*;
    import java.util.jar.*;
    import java.io.*;
     
    public class JarTreeElement {
     
       public final static String Version = "JarTreeElement 6 Aug 2005";
     
       final public static String PathSep = "/";
       final public static char PathSepChar = '/';
     
       // Define properties
       String   name;
       String   pathToFile = "";
       boolean  isDirectory;
       long     size;
       long     dateLastModified;
     
       public JarTreeElement root;
       public JarFile jarFile;             // Only in root??
       TreeMap  contents;
     
       final static boolean debug = false; //true;               // Control debug output
     
       //Constructors ------------------------------------------------------------
       public JarTreeElement(String name) {
          this.name = name;
       } // end Constructor
       public JarTreeElement(String name, String path) throws Exception {
          this.name = name;
          loadTree(this, path);
       } // end Constructors
     
       public String getPath() {
          if(name.equals(FileInJar.RootName))
             return "";                    //Don't want path to jar file!  
          else
             return pathToFile;
       }
     
     
       //-------------------------------------------------------------------------
       // Parse jar file entries into a tree structure
       public static void loadTree(JarTreeElement root, String path) throws Exception {
          root.contents = new TreeMap();
          root.pathToFile = path;          // NB root has path to jar file!
          root.isDirectory = true;
          root.contents.put(FileInJar.RootName, root); // pointer to self
     
          try{
             JarFile jf = new JarFile(path);
             root.jarFile = jf;            // Save in root!
             File f = new File(path);
             root.dateLastModified = f.lastModified();
             root.size = jf.size();        // Number of entries
     
     
             // Go thru all the elements in the Jar and place them in tree
             Enumeration jfEn = jf.entries();
             while(jfEn.hasMoreElements()) {
                JarEntry jarEnt = (JarEntry)jfEn.nextElement();
                String jarEntNm = jarEnt.getName();
                if(debug && false)
                   System.out.println(jarEntNm);   
                   /*
                   META-INF/
                   META-INF/MANIFEST.MF
                   xxx/Hello.class
                   xxx/Hello.java
                   xxx/xxx/
                   xxx/xxx/Hello.class
                   xxx/xxx/Moved.java
                   xxx/yyy/
                   xxx/yyy/Hello.java
                   xxx/yyy/Hello.class
                   */         
                JarTreeElement thisJTE = null,
                               currJTE = root;  // Start at top level
                String pPath = "";         // Partial path that will be built
                boolean isDir = jarEntNm.endsWith(PathSep);
                StringTokenizer st = new StringTokenizer(jarEntNm, PathSep);
     
                while(st.hasMoreTokens()) {
                   String nxtNm = st.nextToken();
                   pPath += nxtNm + PathSep;
                   // Now add this to contents
                   thisJTE = (JarTreeElement)currJTE.contents.get(nxtNm);
                   if(thisJTE == null) {
                      thisJTE = new JarTreeElement(nxtNm);
                      thisJTE.root = root;
                      if(isDir || st.hasMoreTokens()) {
                         // its a directory
                         thisJTE.pathToFile = pPath;
                         thisJTE.isDirectory = true;
                         thisJTE.contents = new TreeMap(); // we'll need this
                         if(FileInJar.debug && debug)
                            System.out.println("loadTree()-Added dir " + nxtNm + " to " + currJTE.name);
                      }else {
                         // Not a directory - must be a file
                         thisJTE.pathToFile = jarEntNm;
                         thisJTE.size = jarEnt.getSize();
                         thisJTE.dateLastModified = jarEnt.getTime();
                         if(FileInJar.debug && debug)
                            System.out.println("loadTree()-Added file " + nxtNm + " to " + currJTE.name);
                      }
                      currJTE.contents.put(nxtNm, thisJTE);  // put new entry in table
     
                   } else {
                      // found JTE
                      if(!st.hasMoreTokens()) {
                         System.err.println("loadTree()-Duplicate path to " + jarEntNm + " " + pPath);
                      }
                   }
                   currJTE = thisJTE;      // Advance down path
                } // end while() thru tokens
     
             } // end while() thru jar elements
          }catch(Exception ex) {
             ex.printStackTrace();
             throw ex;
          }
          return;
       } // end loadTree()
     
       //---------------------------------------------------------------------------
       public static JarTreeElement findJTE(JarTreeElement rootJTE, String path) {
          JarTreeElement currJTE = rootJTE;
          StringTokenizer st = new StringTokenizer(path, PathSep);
          while(st.hasMoreTokens()) {
             String nxtPE = st.nextToken(); // next path element
             if(currJTE.contents == null) {
                System.err.println("findJTE() null contents for " + currJTE.name + " with path>" + path);
                return null;
             }
             JarTreeElement nxtJTE = (JarTreeElement)currJTE.contents.get(nxtPE);
             if (nxtJTE == null) {
                System.err.println("findJTE()>>Element not found: " + nxtPE +  " in path " + path
                                  + "\n    looking in: " + rootJTE);
                return null;
             }
             currJTE = nxtJTE;
          } // end while()
          return currJTE;
       } // end findJTE()
     
       //----------------------------------------------------------------------
       public String[] listContents() {
          if(contents == null) {
             System.out.println("listContents() ????contents are null");
             return null;
          }
          Set aSet = contents.keySet();
    //      System.out.println("aSet " + aSet);
          aSet.remove(FileInJar.RootName);  // don't want this returned
          return (String[])aSet.toArray(new String[0]);
       } // end listContents
     
       //---------------------------------------------------------------------
       public String toString() {
          return name + " <path=" + pathToFile + ">";
       }
     
       //-----------------------------------------
       public static String showContents(JarTreeElement root) {
          if(root.contents == null)
             return "No contents";
     
          String leadPad = "  ";
          String retStr = "";
          String[] ent = root.listContents();
     
          for(int i=0; i < ent.length; i++) {
             retStr += ent[i] + "\n";
             JarTreeElement jte = findJTE(root, ent[i]);
             if(jte.contents != null) {
                String[] ent1 = jte.listContents();
                retStr += leadPad + NormsTools.ArrayUtil.toString(ent1) + "\n";
             }
          } // end for(i) 
          return retStr;
       } // end showContents()
     
       // internal method for building path display
       private String showContents(String[] ents, String lPad) {
          String retStr = "";
          return retStr;
       }
     
       //----------------------------------------------------
       // Following for testing - Comment out when done
    /*   public static void main(String[] args) {
          JarTreeElement root = null;
          try {
             root = new JarTreeElement("<Root>", "Testing.jar");
          }catch(Exception ex) { 
             ex.printStackTrace();
          }
    //      loadTree(root, "Testing.jar");
          System.out.println(" Show contents\n" + showContents(root));
          System.out.println("List for xxx/xxx/:" 
                   + NormsTools.ArrayUtil.toString(findJTE(root, "xxx/xxx/").listContents()));
          JarTreeElement jte = findJTE(root, "xxx/xxx/Movedxx.java");
          System.out.println("full path " + jte.getPath());
          System.exit(0);
       } // end main */
    } // end class
    /*   Output >>>>>>>>.
    Running: java NormsTools.InJar.JarTreeElement 
     
     Show contents
    META-INF
      [MANIFEST.MF]
    xxx
      [Hello.class, Hello.java, xxx, yyy]
     
    List for xxx/xxx/:[Helloxx.class, Movedxx.java]
    full path xxx/xxx/Movedxx.java
     
    0 error(s)
    */
    It uses this class:
    // FileInJar - wraps File class for files in Jars
    /*  Changes
      5 Aug 2005 - New Constructor (File, String)
      6 Aug 2005 - Changed toString() to use ourJTE; Added getJTE()
      5 Oct 2006 - Added lastModified()
    */
     
    package NormsTools.InJar;
     
    import java.io.*;
    import java.util.*;
     
    public class FileInJar extends File {
     
       public final static String Version = "FileInJar 5 Oct 2006";
     
       // Global - defines location of all files from now on
       final public static String RootName = "<root>";
     
       public static JarTreeElement root;  // If we're in a jar file
       public static boolean inJar = false;
     
       //----------------------------------------------------
       // Save the root of tree of jar files
       public static void setRoot(JarTreeElement rt) {
          root = rt;                       // Save address
          inJar = true;
       }  // end setRoot()
     
       JarTreeElement ourJTE;              // Our subtree
     
       public static boolean debug = false;  // globally control debug output
     
       //-------------------------------------------------
       // Get an object to read file, depending on ...
       public static File getFile(String fn) {
          if(inJar)
             return new FileInJar(fn);
          else 
             return new File(fn);
       } // end getFile()
       public static File getFile(String dir, String fn) {
          if(inJar)
             return new FileInJar(dir, fn);
          else 
             return new File(dir, fn);
       } // end getFile()
     
       // Constructors ----------------- -----------------------------
       public FileInJar(File dir, String fn) {
          super(dir, fn);
          if(debug)
             System.out.println("FIJ3 for " + dir + " <> " + fn);
          if(inJar) {
             String newDir = fixDir(dir.getAbsolutePath());
             if(newDir.length() > 0 && !newDir.endsWith(JarTreeElement.PathSep)) {
                newDir += JarTreeElement.PathSep;
             }
             ourJTE = JarTreeElement.findJTE(root, newDir+fn);
             if(debug || ourJTE == null) {
                System.out.println("FIJ3-ourJTE: " + ourJTE + " for " + newDir+fn 
                                                 + " (" + dir + ")");
             }
          }
       } // end Constructor3
       public FileInJar(String dir, String fn) {
          super(dir, fn);
          if(debug)
             System.out.println("FIJ2 for " + dir + " <> " + fn);
          if(inJar) {
             String newDir = fixDir(dir);
             if(newDir.length() > 0 && !newDir.endsWith(JarTreeElement.PathSep)) {
                newDir += JarTreeElement.PathSep;
             }
             ourJTE = JarTreeElement.findJTE(root, newDir+fn);
             if(debug || ourJTE == null) {
                System.out.println("FIJ2-ourJTE: " + ourJTE + " for " + newDir+fn 
                                                 + " (" + dir + ")");
             }
          }
       } // end Constructor1
       public FileInJar(String s) {
          super(s);
          if(debug)
             System.out.println("FIJ1 for " + s);
          if(inJar) {
             String newS = fixDir(s);
             ourJTE = JarTreeElement.findJTE(root, newS);
             if(debug || ourJTE == null)
                System.out.println("FIJ1-ourJTE: " + ourJTE + " for " + newS + " (" + s + ")");
          }
       } // end Constructor2
     
       // Strip leading <root> and trailing \
       private String fixDir(String dir) {
          if(dir.startsWith(RootName))
             dir = dir.substring(RootName.length()); // strip rootname
          if(dir.endsWith(File.separator))
             dir = dir.substring(0, dir.length()-1);
          return dir.replace(File.separatorChar, JarTreeElement.PathSepChar);
       }
     
       public JarTreeElement getJTE() {
          return ourJTE;
       }
       //- - - - - - - - - - - - - - - - - - - - - - - - -
       // Override the File methods we use that are different for in jar
       public String[] list() {
          if(inJar) {
             return ourJTE.listContents();
          }else {
             return super.list();
          }
       } // end list()
       public String[] list(FilenameFilter ff) {
          if(inJar) {
             // Following copied from Sun's File.java
          	String names[] = ourJTE.listContents();
          	if ((names == null) || (ff == null)) {
          	    return names;
          	}
          	ArrayList v = new ArrayList();
          	for (int i = 0 ; i < names.length ; i++) {
          	    if (ff.accept(this, names[i])) {
          		    v.add(names[i]);
          	    }
          	}
          	return (String[])(v.toArray(new String[0]));
          }else {
             return super.list(ff);
          }
       } // end list(ff)
     
       public long lastModified() {
          if(inJar) {
             return ourJTE.dateLastModified;
          }else {
             return super.lastModified();
          }
       } // end lastModified()
     
       public boolean isFile() {
          if(inJar) {
             return !ourJTE.isDirectory;
          }else
             return super.isFile();
       }
     
       public boolean isDirectory() {
          if(inJar) {
             return ourJTE.isDirectory;
          }else
             return super.isDirectory();
       }
     
       public boolean exists() {
          if(inJar) {
             return ourJTE != null;        // If found in tree
          }else
             return super.exists();
       }
     
       public String toString() {
          if(inJar)
             return "<InJar> " + ourJTE;
          else
             return super.toString();
       }
     
       public String getAbsolutePath() {
          if(inJar)
             return ourJTE.getPath().replace(File.separatorChar, JarTreeElement.PathSepChar);
          else 
             return super.getAbsolutePath();
       }
    } // end class FileInJar
    Last edited by Norm; October 11th, 2010 at 04:28 PM.