Running a jar file from java code

Hi!
Im trying to run a jar file from my code.
I've tried Classloader, but that doesnt work because it doesnt find the images (also embedded in the 2nd jar file).
WHat I would like to do is actually RUN the 2nd jar file from the first jar file. There must be a way to do this right?
any ideas?

ok, I found some wonderful code (see below) that will try to start the jar. But it doesn't. What it does is produce the following error when my application runs...
So it's not finding the images in the jar file that I am trying to run? Strange. I checked the URL that sending, but it seems ok....
I think I will check the url again to make sure......
any ideas?
Uncaught error fetching image:
java.lang.NullPointerException
     at sun.awt.image.URLImageSource.getConnection(Unknown Source)
     at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
     at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
     at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
     at sun.awt.image.ImageFetcher.run(Unknown Source)
the code....
/* From http://java.sun.com/docs/books/tutorial/index.html */
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
* Runs a jar application from any url. Usage is 'java JarRunner url [args..]'
* where url is the url of the jar file and args is optional arguments to be
* passed to the application's main method.
public class JarRunner {
  public static void main(String[] args) {
    URL url = null;
    try {
      url = new URL(args[0]);//"VideoTagger.jar");
    } catch (MalformedURLException e) {
      System.out.println("Invalid URL: ");
    // Create the class loader for the application jar file
    JarClassLoader cl = new JarClassLoader(url);
    // Get the application's main class name
    String name = null;
    try {
      name = cl.getMainClassName();
    } catch (IOException e) {
      System.err.println("I/O error while loading JAR file:");
      e.printStackTrace();
      System.exit(1);
    if (name == null) {
      fatal("Specified jar file does not contain a 'Main-Class'"
          + " manifest attribute");
    // Get arguments for the application
    String[] newArgs = new String[args.length - 1];
    System.arraycopy(args, 1, newArgs, 0, newArgs.length);
    // Invoke application's main class
    try {
      cl.invokeClass(name, newArgs);
    } catch (ClassNotFoundException e) {
      fatal("Class not found: " + name);
    } catch (NoSuchMethodException e) {
      fatal("Class does not define a 'main' method: " + name);
    } catch (InvocationTargetException e) {
      e.getTargetException().printStackTrace();
      System.exit(1);
  private static void fatal(String s) {
    System.err.println(s);
    System.exit(1);
* A class loader for loading jar files, both local and remote.
class JarClassLoader extends URLClassLoader {
  private URL url;
   * Creates a new JarClassLoader for the specified url.
   * @param url
   *            the url of the jar file
  public JarClassLoader(URL url) {
    super(new URL[] { url });
    this.url = url;
   * Returns the name of the jar file main class, or null if no "Main-Class"
   * manifest attributes was defined.
  public String getMainClassName() throws IOException {
    URL u = new URL("jar", "", url + "!/");
    JarURLConnection uc = (JarURLConnection) u.openConnection();
    Attributes attr = uc.getMainAttributes();
    return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;
   * Invokes the application in this jar file given the name of the main class
   * and an array of arguments. The class must define a static method "main"
   * which takes an array of String arguemtns and is of return type "void".
   * @param name
   *            the name of the main class
   * @param args
   *            the arguments for the application
   * @exception ClassNotFoundException
   *                if the specified class could not be found
   * @exception NoSuchMethodException
   *                if the specified class does not contain a "main" method
   * @exception InvocationTargetException
   *                if the application raised an exception
  public void invokeClass(String name, String[] args)
      throws ClassNotFoundException, NoSuchMethodException,
      InvocationTargetException {
    Class c = loadClass(name);
    Method m = c.getMethod("main", new Class[] { args.getClass() });
    m.setAccessible(true);
    int mods = m.getModifiers();
    if (m.getReturnType() != void.class || !Modifier.isStatic(mods)
        || !Modifier.isPublic(mods)) {
      throw new NoSuchMethodException("main");
    try {
      m.invoke(null, new Object[] { args });
    } catch (IllegalAccessException e) {
      // This should not happen, as we have disabled access checks
}

Similar Messages

  • Running .jar files from Java code

    Hi.
    I am designing a sort of platform to run some games which are saved in .jar files. Basically this platform is a menu from which the user can select the game which he/she wants to run. It also has the feature of adding new games.
    Is is possible to run the .jar file from within java code?
    Thanks for any help!
    Krt_malta

    Just list the jar in the classpath list and call the class in the jar.

  • Running the .class file from java code

    I'm doing a kind of providing service like compiling and running Java code on server side and giving output to the end user.
    Please suggest me an approach with code to run .class file from the Java code.
    import java.io.*;
    public class demo {
    public static void main(String args[]) throws IOException, InterruptedException {
    int result;
    try {
    System.out.println("command output:");
    Process proc = Runtime.getRuntime().exec("java -cp . demoh");
    InputStream in = proc.getInputStream();
    result = proc.waitFor();
    BufferedInputStream buffer = new BufferedInputStream(proc.getInputStream());
    BufferedReader commandOutput = new BufferedReader(new InputStreamReader(buffer));
    String line = null;
    System.out.print(commandOutput);
    try {
    while ((line = commandOutput.readLine()) != null) {
    System.out.print(line);
    System.out.println("command output: " + line);
    }//end while
    commandOutput.close();
    } catch (IOException e) {
    //log and/or handle it
    }//end catc
    } catch (IOException e) {
    System.err.println("IOException raised: " + e.getMessage());
    }

    What happened when you tried what you have there?

  • How to call a .bat file from java code?

    How to call a .bat file from java code? and how can i pass parameters to that .bat file?
    Thanks in advance

    thanks for ur reply
    but still i am getting the same error.
    I am trying to run a .bat file of together tool, my code looks like below
    import java.lang.Runtime;
    import java.lang.Process;
    import java.io.File;
    class SysCall{
         public static void main(String args[]){
              String cmd="D://Borland//Together6.2//bin//Together.bat -script:com.togethersoft.modules.qa.QA -metrics out:D://MySamples//Metrics// -fmt:html D://Borland//Together6.2//samples//java//CashSales//CashSales.tpr";
              //String path="D://Borland//Together6.2//bin//Together.bat ";
              Runtime r= Runtime.getRuntime(); //Declare the system call
              try{
                   System.out.println("Before batch is called");
                   Process p=r.exec(cmd);
                   System.out.println(" Exit value =" + p.exitValue());
                   System.out.println("After batch is called");
              /*can produce errors which must be caught*/
              catch(Exception e) {
                   e.printStackTrace();
                   System.out.println (e.toString());
    I am getting the below exception
    Before batch is called
    java.lang.IllegalThreadStateException: process has not exited
    at java.lang.Win32Process.exitValue(Native Method)
    at SysCall.main(SysCall.java:17)
    java.lang.IllegalThreadStateException: process has not exited

  • Starting exetutable java file from java code

    Hi I was wondering how I can start a executable java file from java code?
    thanks

    Hi Mkaveli,
    Yes, it's possible. If you have a JAR executable, you've just to call the main method of its starter class. For a simple executable class, just call its main method.
    This way :
    SomeStarter.main(null); // if there's no argumentSmall precision : the executable JAR or class must be specified in the classpath of your application.

  • Generation of xml file from java code

    hi,
    I want to manipulate data in a xml file with java code.I have read data from xml file and also changed it. But i am unable to covert it again in xml file from java code. Can you please tell me how i can do this?

    Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
    http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html

  • How to modify an existing xml file from java code.

    Hi
    I have worked on creating a new xml file from java code using xmlbeans.But if i try to modify an already existing file using java code I am unable to get errorfree xmlfile.
    For example if xml file(studlist.xml) is as below:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    Now suppose i have set name to victor using student.setName,
    and set age to 20 using setAge from javacode,
    the new xml file is as follows:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    <Student>
              <Name>victor</Name>
              <Age>20</Age>
         </Student>
    As observed this is not a valid xml file.But how can i modify without any errors?

    I know it's an old post, but I found this while doing a google search for something else, and don't like to leave it un-aswered
    Just in case anyone has a similar problem... In this case the new elements have been appended outside of the root element
    What you need to do is first get the root element and then append the new children to that, there are several ways of getting the root element, which depend on what you want to do with the elements you get back here's a simple (incomplete) way.
    // gets the root element of the specified file (code not shown)
    Element rootElement= new SAXReader().read(file).getRootElement();Then just append the new elements as below (this is non-generic code and would need to be modified for your situation)
    // write a new student element
    Element student = document.createElement("Student");  // creates the new student
    rootElement.appendChild(student); // ***appends it to the root element***
    Element name = document.createElement("Name"); // creates the name element
    name.appendChild(document.createTextNode("Fred")); // adds the name text to the name element
    student.appendChild(name); // appends the name to the student
    Element age= document.createElement("Age"); // creates the age element
    age.appendChild(document.createTextNode("26")); // adds the age text to the age element
    student.appendChild(age); // appends the name to the studentThen flush ya buffers or whatever and write the file
    Edited by: Dream-Scourge on Apr 23, 2008 11:10 AM

  • How to pass arguments to a batch file from java code

    Hi
    I have a batch file (marcxml.bat) which has the following excerpt :
    @echo off
    if x==%1x goto howto
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; %1 %2 %3
    goto end
    I'm calling this batch file from a java code with the following line of code:
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat");
    so ,that invokes the batch file.Till that point its ok.
    since the batch file accpets arguments(%1 %2 %3) how do i pass those arguments to the batch file from my code ...???
    %1 is a classname : for ex: gov.loc.marcxml.MARC21slim2MARC
    %2 is the name of the input file for ex : C:/Downloads/Marcxml/source.xml
    %3 is the name of the output file for ex: C:/Downloads/Marcxml/target.mrc
    could someone help me...
    if i include these parameters too along with the above line of code i.e
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat gov.loc.marcxml.MARC21slim2MARC C:\\Downloads\\Marcxml\\source.xml C:\\Downloads\\Marcxml\\target.mrc") ;
    I get the following error :
    Exception in thread main java.lang.Noclassdef foundError: c:Downloads\marcxml\source/xml
    could some one tell me if i'm doing the right way in passing the arguments to the batch file if not what is the right way??
    Message was edited by:
    justunme1

    1 - create a java class (Executer.java) for example:
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class Executer {
         public static void main(String[] args) {
              try {
                   for (int i = 0; i < args.length; i++) {
                        System.out.println(args);
                   Class<?> c = Class.forName(args[0]);
                   Class[] argTypes = new Class[] { String[].class };
                   Method main = c.getDeclaredMethod("main", argTypes);
                   // String[] mainArgs = Arrays.copyOfRange(args, 1, args.length); //JDK 6
                   //jdk <6
                   String[] mainArgs = new String[args.length - 1];
                   for (int i = 0; i < mainArgs.length; i++) {
                        mainArgs[i] = args[i + 1];
                   main.invoke(null, (Object) mainArgs);
                   // production code should handle these exceptions more gracefully
              } catch (ClassNotFoundException x) {
                   x.printStackTrace();
              } catch (NoSuchMethodException x) {
                   x.printStackTrace();
              } catch (IllegalAccessException x) {
                   x.printStackTrace();
              } catch (InvocationTargetException x) {
                   x.printStackTrace();
              } catch (Exception e) {
                   e.printStackTrace();
    2 - create a .bat file:
    @echo off
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; Executer %TARGET_CLASS% %IN_FILE% %OUT_FILE%3 - use set command to pass variable:
    Open MS-DOS, and type the following:
    set TARGET_CLASS=MyTargetClass
    set IN_FILE=in.txt
    set OUT_FILE=out.txt
    Then run your .bat file (in the same ms dos window)
    Hope that Helps

  • Run chm help file through java code

    hello,
    would you tell me how can i run a help.chm file using java code. i am trign this but no luck.
    first try
    Process pp=run.exec("C:/Program Files/Internet Explorer/IEXPLORE.exe ./res/bobftphelp.chm" );
    Second try
              Process pp=run.exec(" ./res/bobftphelp.chm" );
    It run fine a help.doc file but not help.chm file.
    please help me
    Thanka in advance
    Ravi Charan

    The second address given to that function, does it relate to the class that its being called from? cause i've got
    Runtime.getRuntime().exec("C:\\WINDOWS\\hh.exe .\\HelpFile_9_3.chm" );where HelpFile_9_3 is in the same folder as my class, but it won't work. Can anyone help?
    Also, can you search within a chm file from Java? If I get that above code working, I presume it'll open the help file to the main page. I'd like to search within that document for a word or phrase - possible?
    Thanks!
    Edited by: Pulkse.co.uk on Sep 10, 2008 8:18 AM

  • How to run a jar file using Java application.

    Hi all,
    I know that jar file can run using the following command, using the command prompt.
    java -jar jar-fileBut I don't know how to run that command through a Java code. Hope it's clear to you.
    So can you please explain how can I do it.
    Thanks,
    itsjava

    rayon.m wrote:
    The solution given by ropp appears to have nothing to do with what you asked about.Ok sir, I got the point.
    I've try a test as follows. But it doesn't give any output. Even not an exception.
            try {
                String[] temp = new String[]{"java", " -jar", " MainApp.jar"};
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(temp);
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);
                System.out.println("Temp_Values");
            catch(InterruptedException ex) {
                System.out.println(ex.getMessage());
            catch (IOException ex) {
                System.out.println(ex.getMessage());
            }I've debug and see, but the exitValue is even not exist at run time. Can you tell me where I'm going wrong.

  • OpenScript/How to add .jar file to Java Code in relative path

    Hi all,
    I want to add a .jar file which can be executed separately (like "java -jar A.jar") to my recorded Java Code.I've read this wiki http://everest2.us.oracle.com/wiki/Generic_JAR_Project about how to add a .jar file to "Assets", however, I cannot figure out how to use the .jarr file in Java code,I mean , how to get this .jar file like the method the databank added in "Assets"?
    Things I did are as followed:
    1.Execute my .jar file in OpenScript Java code with absolute path like this:
    String cmd = "C:\Users\A.jar";
    Runtime.getRuntime().exec(cmd);
    This does work, but must set a absolute path in Java code like "C:\User\A.jar" ,which is not the workaround I want (I need my scripts can be run on other machines).
    2.Try to get its current path with following codes:
    File directory = new File(".");
    String currentPath=directory.getCanonicalPath();
    However,though this can get its absolute path (which is the the project path) in Eclipse like "C:\Users\Workspace\testProject", this only gets "C:\OracleATS\openScript" in OpenScript.
    I thought to copy my .jar file to the project path , got its current path in java code first,then can know the path of .jar file, but this workaround failed because of the above reason.
    I notice that in the "Assets" there are "Databanks","Object Libraries","JAR Files","Scripts". Since the databanks and scripts that added to "Databanks" and "Scripts" can be got or run in Java Code like:
    *getDatabank("DatabankName").getNextDatabankRecord(); String data = eval("{{db.DatabankName.data}}");*
    *or getScript("ScriptName").run();*
    *Is there a method to get and run the jar file added to "Assets\JAR Files" like the above?*
    Thank you very much!
    Regards,
    Angyoung

    Hi DM,
    Thanks for your reply!
    I've found a workaround,which is calling OpenScript's APIs ,such as this.getScriptPackage().getRepository() and this.getScriptPackage().getWorkspace(),etc to locate the .jar file.
    And this workaround can still work even though the script is run on other machine.
    Sorry to reply you so late!
    Regards,
    Angyoung

  • Running an exe file from java

    Hi , can anyone tell me how to run an exe file from my java program. the exe is in the same directory as my java files . When i click on a button i want to put something in the actionPerformed() method which will launch the exe file - prog.exe
    Hope someone can help me.
    Thanks Jim

    Hi !
    Look at the RunTime class...

  • How to copy a file from Java code

    I have written a file through Java code in folder, say, "A". Now, I want a copy of that file exactly the same in some other folder "B". How, it can be done?

    http://java.sun.com/docs/books/tutorial/essential/io/streams.html

  • Call .bat file from java code

    I need to call an application that uses a .bat file to execute from a java program. Is that possible?
    This is the .bat file:
    importcli.exe ciaf2735 C:\Importcli\files\SAI2735*.txt  
    importcli.exe ciaf2735 C:\Importcli\files\CI2735*.txt  
    importcli.exe ciaf2735 C:\Importcli\files\SC2735*.txt  
    importcli.exe db1800 C:\Importcli\files\*.mdb

    magaupe wrote:
    I need to call an application that uses a .bat file to execute from a java program. Is that possible?
    This is the .bat file:
    importcli.exe ciaf2735 C:\Importcli\files\SAI2735*.txt  
    importcli.exe ciaf2735 C:\Importcli\files\CI2735*.txt  
    importcli.exe ciaf2735 C:\Importcli\files\SC2735*.txt  
    importcli.exe db1800 C:\Importcli\files\*.mdb
    Hmmm, I wonder what would happen if there were a web search engine and you could research like this:
    [http://www.google.com/search?hl=en&q=call+.bat+file+from+java]

  • Running Oracle startup or shutdown bat file from Java code

    I have two bat files for the startup and shutdown of Oracle instance which works fine from the command prompt. But my requirement is to run it through a Java program. Please reply with full Java code. Also mention how I would get the status of the bat files that it is successfully executed or not and if not what is the error.

    Your program is working fine, but there is another problem. What's happening now is I have to open the Login screen after the startup of oracle server is complete, but the next line of my program after Runtime.exec is the LoginScreen.show which immediately shows the login screen after executing Runtime.exec and when I am giving the login name and password and press enter, it shows Oracle not available exception, because the startup process is still in progress. I want to stop the execution of my next line of code until and unless my process of Oracle startup is complete.

Maybe you are looking for