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

Similar Messages

  • 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 from own jar file

    Using netBeans IDE 4.1 I wrote a stand-lone application contained in a single jar file. It transforms xml files into drawings. I'd like to distribute the application with some sample xml-files in that one jar-file. But how can I make the application read these embedded files?
    I looked at the SplitPaneDemo that uses a list of images to display.
    http://java.sun.com/docs/books/tutorialJWS/uiswing/components/example-1dot4/SplitPaneDemo.jnlp
    works.
    I also downloaded
    http://java.sun.com/docs/books/tutorialNB/download/tut-examples.zip
    extracted uiswing/components/example-swing
    created a new project from existing sources
    made SplitPaneDemo the main class
    and run it after a clean build.
    The images are in the jar-file, but no images appear.
    Is the problem in the second attempt a missing classpath? In that case: how can I prevent my a-technical users having to set a classpath, or how can I find out and use the absulute path to the jar-file?
    Jo

    But my browser (FireFox 1.0.7 on Windows XP Home edition) isn't launched (and no error shown) with
    String url = "" +getClass().getClassLoader().getResource("path/to/page.html");
    try {
                Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url);
    } catch (java.io.IOException e) {
                javax.swing.JOptionPane.showMessageDialog
                        ( this
                        , url
                        , "debug info"
                        , javax.swing.JOptionPane.INFORMATION_MESSAGE
    }

  • 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.

  • Need help compiling external jar files into my one jar file from cmd line

    Here is my problem, let me see if I can explain it right:
    I am making a jar file on my development computer that will run my java project. In this java project, it references a couple Java3D jar files. On my development computer, I create the jar file and it runs correctly, but when I move that jar file over to the test computer, the parts of the application needing those Java3D jars are not found in my jar I created. I isolated the problem and it is because those Java3D jar files I needed are not on my test machine. But that is the way I need it to be. I need it so that when I compile all my code on the development machine, I need it to also compile those two Java3D files into my one jar that I move to the test machine. You get what I'm saying? I must do all the compiling from the command line and have only one jar file to put on the test machine that contains all my compiled code and the two Java3D files needed to run some of the applications in the project.
    Here a brief sample of what I'm doing:
    To compile my java files in my project, I simply to this for all my files:
    javac file.java
    javac file2.java... and so on for all my java files.
    Then I create my jar file:
    jar -cfm MyJar.jar manifest.mf file.class
    jar -fmu MyJar.jar manifest.mf file2.class... and so on for all my class files.
    Also when compiling my jar file, I do this thinking that it would include the two Java3D jars into my one jar file:
    jar -fmu MyJar.jar manifest.mf jars/j3d-org-images.jar
    jar -fmu MyJar.jar manifest.mf jars/j3d-org.jar
    My manifest file looks something like this:
    Manifest-Version: 1.0
    Main-Class: Main
    Class-Path: jars/j3d-org.jar jars/j3d-org-images.jar
    Do I have to have that Class-Path in there pointing to those jar files? Those jar files will not exist on my test machine because the directory structure will not be the same. I've tried a manifest without specifying my Class-Path to those jar files, but I get the same problem when I run my application on the part that needs the Java3D files.
    The error I am getting is that there is a RasterTextLabel class inside one of those Java3D jar files that my application cannot access because those jar files are not on my test machine.
    So basically what I really need to know is how I get those two Java3D jar files compiled into my one jar file that I move to a test machine and run with the following command:
    java -jar MyJar.jar
    Can anyone help me??
    Thanks.

    Here what you need is to have all the files present in a single jar file, and the classpath is set properly to the required jar files.
    Do the following in steps:
    1)
    Create a custom manifest file,say mymanifest.mf, with the following contenets, put it in current directory:
    Manifest-Version: 1.0
    Created-By: 1.4.0_01 (Sun Microsystems Inc.)
    main-Class: Main
    Class-Path: jars/j3d-org.jar jars/j3d-org-images.jar <press ENTER key>
    2)
    jar -cfm MyJar.jar manifest.mf file.class
    jar -fmu MyJar.jar manifest.mf file2.class... and so on for all class files.
    3)
    jar -fmu MyJar.jar manifest.mf jars/j3d-org.jar
    jar -fmu MyJar.jar manifest.mf jars/j3d-org-images.jar
    (Make sure that j3d-org-images.jar and j3d-org.jar are present in a subdirectory called 'jars')
    Now you would be able to run,
    java -jar myjar.jar

  • 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

  • I have a new Macbook Pro - trying to migrate files etc from my Macbook Air using a Thunderbolt Cable between the two.  I follow the directions but the two computers never "discover" each other.  WiFi connect works but 70 hours is a rough deal.

    I have a new Macbook Pro.  Trying to migrate files etc from my Macbook Air using a Thunderbolt Cable between them.
    I follow the directions but the two computers never "discover" each other - using a WiFi connection works but 70 hours is a rough deal.
    (Mac OS 10.8.2 on both computers)

    Are you trying target disk mode?
    http://support.apple.com/kb/PH10725
    Ciao

  • 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.

  • Read images from a jar file?

    Hello, I'm converting a 6i app to 10g. This app does a ton of read_image_file() calls to
    change GIF images on the screen based on user actions. In 6i the images are all stored on the local hard drive. The images are not icons for buttons, but images that appear in different locations on the screen.
    For 10g, is it possible to leave the images in a jar file and effectively read the images from that? Otherwise, I suppose I'm looking at using webutil functionality to download the jar file and unjar it into an images directory for reading from the client?
    Any best-practice scenario for this sort of thing?
    Thanks for any info,
    Gary

    We are migrating from 6i to 10g too. And I try to not use webutil. All my pictures (icons gif files) are in a jar file.
    Just make attention of the size of your pictures. The jar file is loaded when you launch the application (the first time, and after, only if the jar file has changed).

  • I have a new iMac and want to transfer files etc from my old iMac with an ethernet cable

    i have a new imac and want tot ransfer files etc from my old imac using an ethernet cable

    Connect them together with Ethernet cable and use Setup Assistant.

  • 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.

Maybe you are looking for

  • Adobe AIR Seamless Install Badge PROBLEM

    Hello, my air badge installation stop working few days back (do not know exactly how many). Has anybody else this issue here? Any advice probably. Thanks

  • Constraints on the Special Ledger

    Hi All I need a bit of expert advise on a solution that I proposed: I  have a client requirement where they wanted to implement a parallel currency to an existing co code, they are on SAP 4.7. We proposed a new company code as the solution with a new

  • Finance and Controlling report in combination with Cost center, GL account, Internal Order

    Hi Members, Finance and Controlling report in combination with Cost center, GL account, Internal Order. Please provide any slandered report in all 3 dimension. Thanks Dileep Kumar

  • Clean my under the hood

    I have been experimenting in the past with terminal configure&make&make install combo. And I'm pretty sure it has crap left everywhere. 1) How do I clean that staff without effecting my TeX and GnuPG? 2) Don't want to do clean install 3) I defiantly

  • Itunes library bigger than ipod

    My itunes library has more songs than my ipod will hold. What is the best way for me to choose what actually goes on the ipod?