Directory listing from a JAR file

Hi,
I want to know how i can get a list of files in a certain directory located inside a jar file.
Thanks

Programmatically, you need to parse the JAR with the help of java.util.zip.
From the command prompt, you can do it with "jar -t archive.jar"

Similar Messages

  • Directory listing from my OS X 10.5.8 server into a text file

    Does anyone know how I can get a directory listing from my server, which I can put into an Excel Spreadsheet?
    Thanks

    Download the free TextWrangler and drag the enclosing folder into it. Alternatively, open the AppleScript Editor in the /Applications/Utilities/ folder, paste the following in:
    do shell script "ls -AR " & quoted form of POSIX path of ((choose folder) as alias) & " >> ~/Desktop/inventory.txt"
    and run it as is.
    (104088)

  • Running scripts, bat files, etc from a jar file

    Hello,
    Does anyone know of a way, or even if it is possible to run a script or batch file from a jar file?
    For instance, lets say I have a batch file that I can run from the command prompt by typing :
    myBatchFile.bat
    and now I write a very simple java app that will do the same:
    public class Test {
    public static void main(String[] args) {
    try {
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(�myBatchFile.bat�);
    } catch (Exception e) {
    e.getMessage();
    The above app will work as long as the batch file is in the current directory, but how or can I make it work if I stick the batch file in a jar file along with the app?
    I tried using the manifest file with no luck.
    I tried creating a URI to the jar file, wrapping it in a File and then passing that File to the exec method also with no luck.
    I searched all the forums on Sun but came up with nothing.
    I performed a google search also with no luck.
    Does anyone have the answer to this? Even if I can get a definitive �No it can�t be done� answer. Although I would think that it should be able to be done.
    Thanks

    Hi,
    you cannot execute anything being inside a jar-file. The OS doesn't know anythig about jar-files and cannot look inside one to find the program/script/batch you want to execute.
    You could do a workaround by extracting the file from the jar-file before calling exec(). But normally OS dependent files should not be inside a jar-file and remain in a own directiory.
    Andre

  • Executing an file.exe from a jar file?

    Does anyone know how to execute an *.exe file from jar file?
    I have two files that I want to execute in one java.class, Monview.exe and Moninit.exe. Both are stored in the same jar file as the class called link.class.
    This is my code to run one of the files from the hard drive
    String []cmd={"c:\\monview.exe"};
    try
    Process pr = Runtime.getRuntime().exec(cmd);
    StringBuffer buf = new StringBuffer();
    InputStream istr = pr.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(istr));
    String str;
    while ((str = br.readLine()) != null) {      
                             buf.append(str);
    try {       
    pr.waitFor();
    } catch (InterruptedException e) { }
         if (pr.exitValue() != 0) {      
         br.close();
    catch (IOException e){}
    It works when i place both .exe on the local host harddrive but when I place it in the jar file nothing happens. Could anyone help me please on why does this happen and how I can fix it? Or on how to get the link.class code to extract it from the jar file and place it on the system directory and delete it from the system directory, without it knowing where the jar file comes from?

    Hello,
    If I am not mistaken, by including the JAR file in the CLASSPATH (specifying the absolute path), or after the -classpath option after the java command (java -classpath jar_archive main_class), the system will find both files in the JAR archive.
    Hope this helps!

  • Read images from external jar file (Sun's Java L&F Graphics repository)

    Hi!
    I don't know how to read images from an external jar file. Sun has a Java Look and Feel graphics repository that contains a lot of good images that can be used on buttons and so on. This repository is delivered as a jar file, containing only images, and I want to read the image files from that jar file directly without including them inside my application jar file. The application and image jar files will be in the same directory.
    I have absolutely no clue how to solve this. Is it necessary to include the images inside my application jar file or is it possible to have them separate as I want.
    Would really appreciate some help!
    Best regards
    Lars

    Hi,
    There is two ways :
    1) Add your jarfile to the classpath.
    Use the class loader :
    URL url = ClassLoader.getSystemResource("your/package/image.gif");
    Image im = (new ImageIcon(url)).getImage();
    or
    Image im = Toolkit.getDefaultToolkit().getImage(url);2)If you don't want to add the jar to the classpath you can use this (under jdk 1.4):
    import java.util.*;
    import java.util.jar.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class ImageUtilities {
         public static Image getImage(String jarFileName, String fileName) {
              BufferedImage image = null;
              try {
                   JarFile jar = new JarFile(new File(jarFileName), false, JarFile.OPEN_READ);
                   JarEntry entry = jar.getJarEntry(fileName);
                   BufferedInputStream stream = new BufferedInputStream(jar.getInputStream(entry));
                   image = ImageIO.read(stream) ;
              catch (Exception ex) {
                   System.out.println(ex);
              return(image);
    }I hope this helps,
    Denis

  • Reading parameters lists from a text file

    Hi All,
    Using CR XI R2 with VB6  and external .rpt files - - - - -
    In a VB6 app I use VB to loop through my tables to create dynamic parameter lists (CR XI is limited to the number of parameters it can create from the table). This works well but each time the user refreshes the report the same code is run to re-create the parameter list which is redundant and slows down the report(s).
    Is it possible to manually create a series of text files - say each morning - and then read the parameter lists from the text file(s) at runtime instead of doing it on the fly each time?
    Thanks in advance!
    Peter Tyler
    Geneva - Switzerland

    I find this sentence confusing:
    Is it possible to manually create a series of text files - say each morning - and then read the parameter lists from the text file(s) at runtime instead of doing it on the fly each time?
    Typically, runtime means on the fly - I think...
    So, I'm not sure if you are trying to read a saved data report and filter that saved data so that you do not have to hit the database(?).
    Creating a text file is beyond the support of this forum, though that should be a trivial exercise. Reading a text file and passing the results to a parameter is the same thing you are doing already, so I'm not sure where the hang up would be here(?)
    Or - rather than creating a text file, why not create a temp table and query it as you do when you loop through the tables to create dynamic parameter lists(?).
    I'm pretty lost here...
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

  • Reading an xml file from a jar file

    Short question:
    Is it possible to read an xml file from a jar file when the dtd is
    placed inside the jar file? I am using jdom (SAXBuilder) and the default
    sax parser which comes with it.
    Long Question:
    I am trying to create an enterprise archive file on Weblogic 6.1. We
    have a framework that is similar to the struts framework which uses it's
    own configuration files
    I could place the dtd files outside the jar ear file and specify the
    absolute path in an environment variable in web.xml which is
    configurable through the admin console.
    But I want to avoid this step and specify a relative path within the jar
    file.
    I have tried to use a class which implements the entityresolver as well
    as try to extend the saxparser and set the entity resolver within this
    class explicitly, but I always seem to sun into problems like:
    The setEntityresolver method does not get called or there is a
    classloader problem. i.e. JDOM complains that it cannot load My custom
    parser which is part of the application
    Vijay

    Please contact the main BEA Support team [email protected]
    They will need to check with product support to determine
    the interoperatablity of Weblogic Server with these other
    products.

  • How to add multiple images to a JLabel from the jar file

    I want to add multiple images in a JLabel but the icon property only allows me to add one. I thought I could use html rendering to add the images I need by using the <img> tab, but I need to use a URL that points to the image.
    How do I point to an image inside the jar file? If I can't, is there another way to show multiple images in a JLabel from the jar file?

    Thanks, it works perfectly. It's a really smart way of fixing the problem too :)
    I also found your toggle button icon classes which is something I've also had a problem with.
    Thanks.

  • Urgent help for processing XML stream read from a JAR file

    Hi, everyone,
         Urgently need your help!
         I am reading an XML config file from a jar file. It can print out the result well when I use the following code:
    ===============================================
    InputStream is = getClass().getResourceAsStream("conf/config.xml");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;
    while ((line = br.readLine()) != null) {
    System.out.println(line); // It works fine here, which means that the inputstream is correct
    // process the XML stream I read from above
    NodeIterator ni = processXPath("//grid/gridinfo", is);
    Below is the processXPath() function I have written:
    public static NodeIterator processXPath(String xpath, InputStream byteStream) throws Exception {
    // Set up a DOM tree to query.
    InputSource in = new InputSource(byteStream);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setNamespaceAware(true);
    Document doc = dfactory.newDocumentBuilder().parse(in);
    // Use the simple XPath API to select a nodeIterator.
    System.out.println("Querying DOM using " + xpath);
    NodeIterator ni = XPathAPI.selectNodeIterator(doc, xpath);
    return ni;
    It gives me so much errors:
    org.xml.sax.SAXParseException: The root element is required in a well-formed doc
    ument.
    at org.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1213
    at org.apache.xerces.framework.XMLDocumentScanner.reportFatalXMLError(XM
    LDocumentScanner.java:570)
    at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.endO
    fInput(XMLDocumentScanner.java:790)
    at org.apache.xerces.framework.XMLDocumentScanner.endOfInput(XMLDocument
    Scanner.java:418)
    at org.apache.xerces.validators.common.XMLValidator.sendEndOfInputNotifi
    cations(XMLValidator.java:712)
    at org.apache.xerces.readers.DefaultEntityHandler.changeReaders(DefaultE
    ntityHandler.java:1031)
    at org.apache.xerces.readers.XMLEntityReader.changeReaders(XMLEntityRead
    er.java:168)
    at org.apache.xerces.readers.UTF8Reader.changeReaders(UTF8Reader.java:18
    2)
    at org.apache.xerces.readers.UTF8Reader.lookingAtChar(UTF8Reader.java:19
    7)
    at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.disp
    atch(XMLDocumentScanner.java:686)
    at org.apache.xerces.framework.XMLDocumentScanner.parseSome(XMLDocumentS
    canner.java:381)
    at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1098)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.
    java:195)
    at processXPath(Unknown Source)
    Thank you very much!
    Sincerely Yours
    David

    org.xml.sax.SAXParseException: The root element is required in a well-formed document.This often means that the parser can't find the document. You think it should be able to find the document because your test code could. However if your test code was not in the same package as your real (failing) code, your test is no good because getResourceAsStream("conf/config.xml") is looking for that file name relative to the package of the class that contains that line of code.
    If your test code wasn't in any package, put a slash before the filename and see if that works.

  • Problem parsing XML with schema when extracted from a jar file

    I am having a problem parsing XML with a schema, both of which are extracted from a jar file. I am using using ZipFile to get InputStream objects for the appropriate ZipEntry objects in the jar file. My XML is encrypted so I decrypt it to a temporary file. I am then attempting to parse the temporary file with the schema using DocumentBuilder.parse.
    I get the following exception:
    org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element '<root element name>'
    This was all working OK before I jarred everything (i.e. when I was using standalone files, rather than InputStreams retrieved from a jar).
    I have output the retrieved XML to a file and compared it with my original source and they are identical.
    I am baffled because the nature of the exception suggests that the schema has been read and parsed correctly but the XML file is not parsing against the schema.
    Any suggestions?
    The code is as follows:
      public void open(File input) throws IOException, CSLXMLException {
        InputStream schema = ZipFileHandler.getResourceAsStream("<jar file name>", "<schema resource name>");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
          factory.setNamespaceAware(true);
          factory.setValidating(true);
          factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
          factory.setAttribute(JAXP_SCHEMA_SOURCE, schema);
          builder = factory.newDocumentBuilder();
          builder.setErrorHandler(new CSLXMLParseHandler());
        } catch (Exception builderException) {
          throw new CSLXMLException("Error setting up SAX: " + builderException.toString());
        Document document = null;
        try {
          document = builder.parse(input);
        } catch (SAXException parseException) {
          throw new CSLXMLException(parseException.toString());
        }

    I was originally using getSystemResource, which worked fine until I jarred the application. The problem appears to be that resources returned from a jar file cannot be used in the same way as resources returned directly from the file system. You have to use the ZipFile class (or its JarFile subclass) to locate the ZipEntry in the jar file and then use ZipFile.getInputStream(ZipEntry) to convert this to an InputStream. I have seen example code where an InputStream is used for the JAXP_SCHEMA_SOURCE attribute but, for some reason, this did not work with the InputStream returned by ZipFile.getInputStream. Like you, I have also seen examples that use a URL but they appear to be URL's that point to a file not URL's that point to an entry in a jar file.
    Maybe there is another way around this but writing to a file works and I set use File.deleteOnExit() to ensure things are tidied afterwards.

  • Is it possible to load classes from a jar file

    Using ClassLoader is it possible to load the classes from a jar file?

    URL[] u = new URL[1] ;
    u[0] = new URL( "file://" + jarLocation + jarFileName + "/" );
    URLClassLoader jLoader = new URLClassLoader( u );
    Object clsName = jLoader.loadClass( clsList.elementAt(i).toString() ).newInstance();
    I get this error message.
    java.lang.ClassNotFoundException: ExceptionTestCase
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:297)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:253)
    // "file://" + fileLocation + fileName + "/" This works fine from a browser.
    Is there anything I am missing? Thanks for the reply.

  • Issues with Loading Images from a Jar File

    This code snippet basically loops through a jar of gifs and loads them into a hashmap to be used later. The images all load into the HashMap just fine, I tested and made sure their widths and heights were changing as well as the buffer size from gif to gif. The problem comes in when some of the images are loaded to be painted they are incomplete it looks as though part of the image came through but not all of it, while other images look just fine. The old way in which we loaded the graphics didn't involve getting them from a jar file. My question is, is this a common problem with loading images from a jar from an applet? For a while I had tried to approach the problem by getting the URL of the image in a jar and passing that into the toolkit and creating the image that way, I was unsuccessful in getting that to work.
    //app is the Japplet
    MediaTracker tracker = new MediaTracker(app);
    //jf represents the jar file obj, enum for looping through jar entries
    Enumeration e = jf.entries();
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    //buffer for reading image stream
    byte buffer [];
    while(e.hasMoreElements())
    fileName = e.nextElement().toString();
    InputStream inputstream = jf.getInputStream(jf.getEntry(fileName));
    buffer = new byte[inputstream.available()];
    inputstream.read(buffer);
    currentIm = toolkit.createImage(buffer);
    tracker.addImage(currentIm, 0);
    tracker.waitForAll();
    images.put(fileName.substring(0, fileName.indexOf(".")), currentIm);
    } //while
    }//try
    catch(Exception e)
    e.printStackTrace();
    }

    compressed files are not the problem. It is just the problem of the read not returning all the bytes. Here is a working implementation:
    InputStream is = jar.getInputStream(entry);
    ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
    try{
    byte[] buf = new byte[1024];
    int read;
    while((read = is.read(buf)) > 0) {
    os.write(buf, 0, read);
    catch(Exception e){
         e.printStackTrace();
         return null;
    image = Toolkit.getDefaultToolkit().createImage(os.toByteArray());
    This works but I think you end up opening the jar a second time and downloading it from the server again. Another way of getting the images is using the class loader:
    InputStream is = MyApplet.class.getResourceAsStream(strImageName);
    In this case, the image file needs to be at the same level than MyApplet.class but you don't get the benefit of enumerating of the images available in the jar.

  • How to read a text file from a Jar file

    Hi
    How can I read a text file from a Jar file?
    Thanx in advance..

    thanx
    helloWorld it works.damn, I didn't remove it fast enough. Even if it is urgent, it is best not to mention it, telling people just makes them take longer.

  • How to call a function from a JAR file

    Hi ALL,
    I am trying to call a Public function from a JAR file from my JAVA
    file. Can you please provide an example or suggest a good resource?
    Basically my java file Test.Java should call a function called 'export_a_doc' from a JAR file Export.jar. How do I refer this in my Java file and call 'export_a_doc'?
    Thanx

    Hi,
    HERE IS MY JAVA FILE
    // We need this for Starting our Export Process
    import com.newexport.Myclass;
    public class MyTest {
         // Our function to Start Export
         protected static void test(String[] args) {
         System.out.println("Starting. \n---------------------");
         Myclass p = new Myclass();
         try {
    p.Start_Export(args);
    System.out.println("Finished. \n---------------------");
         } catch(Exception e) {
    e.printStackTrace();
         public static void main(String[] args) {
         test(args);
    HERE IS THE BATCH FILE TO BUILD AND RUN
    cd \JNI\Srcs
    echo "-------------"
    c:\JBuilder7\jdk1.3.1\bin\javac -classpath C:\JNI\Export.jar MyTest.java
    echo "-------------"
    \JBuilder7\jdk1.3.1\bin\java.exe -classpath c:\JNI\Export.jar MyTest
    The Export.jar uses other jar files
    Raj

  • Executing .jar files from another .jar file.

    How would I run one .jar file from another .jar file. and is there anyway to call specific class arguments? Because I have one .jar file that reads a specified file and returns its contents.
    So how would I execute it and specify its arguments and how would I make it return something to the executing jar file?

    Because I have one .jar file that reads
    a specified file and returns its contents. Presumably you have a class that does that, and you have that class stored in a jar. And you want to know how to... um... do something with that class. I say "um..." because normally you don't execute a class, either, you either call its static methods or you create an instance of the class and call its instance methods.
    If you have been writing a whole lot of little classes each of which just has a static main method, then stop doing that. Write real Java classes instead. The tutorial is here:
    http://java.sun.com/docs/books/tutorial/java/index.html

Maybe you are looking for

  • Sony Xperia Z1 Water Resistivity false advertising and poor service from service center

    I have bought Sony Xperia Z1 from eBay on 31 October 2013. I have been using this phone for nearly a year. The phone was good in performance but comes to water resistivity it will resist water for a few months but after few months even though the car

  • HT2494 iMac headphone jack stopped working

    Hi folks The headphones are not working any more on my iMac and nothing has apparently changed. They were working yesterday. Have tested several other sets of phones and an external speaker system too - no go. The headphone output choice suddenly doe

  • Safari Not Showing Web Address in Address Bar after Lion Update

    Sometimes the address bar is blank (save the "Go to this address" message.) Other times, it reads only the hompage address for a site I visit. For example, if I'm reading CNN.com, it will only show "www.cnn.com" no matter what page within cnn.com I g

  • Problem in Data Upload

    Hai Guys, I am facing one problem when i am uploading data. Now only we have created R3 production source system. In the R3 system datasource having data. But when i am uploading the data in BW system, it is giving only 0 records. Any settings is mis

  • ExcuteParms throws error

    Using jdev11.1.1.5.0-adfbc this is example shows my requirement. https://blogs.oracle.com/shay/entry/adding_an_lov_to_a_query_param as ditto am trying. but it hits some error while cliking lov.. can anyone point me. where am. <LifecycleImpl> <_handle