Can we run a java application using Runtime.exec()?

Can we run a java application using Runtime.exec()?
If yes what should i use "java" or "javaw", and which way?
r.exec("java","xyz.class");

The best way to run the java application would be to dynamiically load it within the same JVM. Look thru the class "ClassLoader" and the "Class", "Method" etc...clases.
The problem with exec is that it starts another JVM and moreover you dont have the interface where you can throw the Output directly.(indirectly it can be done by openong InputStreams bala blah............). I found this convenient. I am attaching part of my code for easy refernce.
HIH
ClassLoader cl = null;
Class c = null;
Class cArr[] ;
Method md = null;
Object mArr[];
cl = ClassLoader.getSystemClassLoader();
try{
     c = cl.loadClass(progName.substring(0,progName.indexOf(".class")) );
} catch(ClassNotFoundException e) {
System.out.println(e);
     cArr = new Class[1] ;
     try{
     cArr[0] = Class.forName("java.lang.Object");
     } catch(ClassNotFoundException e) {
     System.out.println(e);
     mArr = new Object[1];
     try{
     md = c.getMethod("processPkt", cArr);
     } catch(NoSuchMethodException e) {
     System.out.println(e);
     } catch(SecurityException e) {
     System.out.println(e);
try {            
processedPkt = md.invoke( null, mArr) ;
} catch(IllegalAccessException e) {
          System.out.println(e);
} catch(IllegalArgumentException e) {
          System.out.println(e);
}catch(InvocationTargetException e) {
          System.out.println(e);
}catch(NullPointerException e) {
          System.out.println(e);
}catch(ExceptionInInitializerError e) {
          System.out.println(e);
}

Similar Messages

  • How can i launch another java application using Runtime class?

    I created a java process which invokes another java application called Launch as shown below,
    Process p=Runtime.getRuntime().exec("java -classpath=C:\\Program Files\\bin\\nettools\\ui\\updates Launch");
    But it is not working...can any one help me on this?
    Edited by: deepakchandaran on Sep 20, 2007 7:10 AM

    You could search the forum and Google.
    it has been answered before.
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • How can I run a java-application on starting of Windows 2000

    How can I run a java-application without any user on starting of Windows 2000?
    For example, if the computer is restarted and nobody enter into it yet, my java-application should run anyway.
    How can I do that?

    Hi, you have to put it in a Windows service.
    To do this you have a program, Srvany.exe that allow to insert a .exe or .bat program in a Windows service.
    For example, i develop a program, TomcatGuardian and i put it in a service because i need to run it in a server without Administrator logged in.
    Regards,
    Ivan.

  • How to capture output of java files using Runtime.exec

    Hi guys,
    I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
    import java.io.*;
    public class CmdExec {
      public CmdExec() {
      public static void main(String argv[]){
         try {
         String line;
         Runtime rt = Runtime.getRuntime();
         String[] cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
         Process proc = rt.exec(cmd);
         cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
         proc = rt.exec(cmd);
         //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
    public class E {
        public static void main(String[] args) {
            System.out.println("hello world!!!!");
    }Please help :)

    Javapedia: Classpath
    How Classes are Found
    Setting the class path (Windows)
    Setting the class path (Solaris/Linux)
    Understanding the Java ClassLoader
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • Running ssh in xterm using Runtime.exec !! URGENT

    I am not able to run the following command using Runtime.exec() but if the same command is executed in shell it gets executed.
    I am working on solais 8
    String toExecStr =
    "xterm -e /bin/sh -c \"ssh [email protected] || echo SSH failed. Press any key to quit.; read a \"";
    System.out.println("Running command :" + toExecStr);
    try {
    Process p = Runtime.getRuntime().exec(toExecStr);
    catch(Exception e){
    e.printStackTrace();
    Any clues .. am i missing something Is there some problem with solaris command ..

    Can some body help me solve this ???

  • How can i built a java application using java debug class on Log4J

    Hi,
    As java API support the MethodEntryEvent, using which I can get the automatic logging statements when the method is entered or exited as HelloExample.main(with argument type).
    Where HelloExample is the class name.
    Main is the method entered with its argument types.
    In some cases I have the o/p as
    -- VM Started --
    ====== main ======
    main -- HelloExample
    callerMethod -- HelloExample
    ====== main end ======
    -- The application exited --
    By using Log4J is there any possibility of getting these sort of o/p along with the loggers supported by Log4J. i mean to say can i built an java application which supports the MethodEntryEvent and MethodExitEvent from java API and also uses the Log4J debugging. I took an e.g. trace example, which (in J2SE 1.4.x or 5.x) will be found in $JAVA_HOME/demo/jpda/examples.jar and unpacking it by
    jar -xvf $JAVA_HOME/demo/jpda/examples.jar i found the com/sun/tools/example/trace/Trace.java and passed the class constructed with logger taken from Log4J. In this case the logging message is displayed on the console. As per the requirement i need to transfer the whole o/p to an output file along with Log4J logger statements. in this case i should not give any command in the cosule except compiling and executing the programme. the programm also should able to run without the main() as i need to integrate Log4J with an application and the code must me application server independent. i need the output as i got using MethodEnteryEvent (shown as above) in case of java application built using Log4J.
    Can any one help me in this regard. can any one give me some suggestion or any programme of this sort. All suggestions are welcomed.
    Thanks & Regards,

    hi,
    can someone help me how to implement logging for method entry parameters and
    method exit return value.
    can someone help me how to use log4j and integrate it to the method entry
    logging and method exit logging.
    Here what i need is without writing the log statements for the method entry and
    method exit i need to log it to the file
    along with other log4j debug statements i provide in the file.I should be able
    to configure whether to enable/disable the logging
    for method entry and method exit. In method entry i should be able to log the
    parameters the method take and in method exit
    i should be able to log te return value to the log file, before the method is
    returned to the callee.
    i hope i am clear
    Thanks in advance.

  • How to run db2 command by using Runtime exec

    Hello
    I am using java. When i am runing db2 command by using Runtime.exec( String cmd, String[] env ). I gave the environment path
    DB2CLP=6259901
    DB2DRIVER=D:\ibm\db2\java\db2java.zip
    DB2HOME=D:\ibm\db2
    DB2INSTANCE=DB2
    DB2MMTOP=D:\CMBISS
    but still I am getting error message
    "DB21061E Command line environment not initialized"
    after setting the above path in the cmd It is working fine. When i am trying thro java programm i am getting the above error. Can I get answer for this.
    bhaski.

    Before you can execute DB2 commands you have to open a DB2 CLP. The following code will do so:
    import java.io.IOException;
    public class Db2 {
         public static void main(String args[]) {
              try {
                   Runtime rt = Runtime.getRuntime();
                   Process child = rt.exec("db2cmd");
                   child.waitFor();
              catch (IOException io) {
                   io.printStackTrace();
              catch (InterruptedException e) {
                   e.printStackTrace();

  • Spawn a java process using runtime.exec() method

    Hi,
    This is my first post in this forum. I have a small problem. I am trying to spawn a java process using Runtime.getRuntime().exec() method in Solaris. However, there is no result in this check the follwoing program.
    /* Program Starts here */
    import java.io.*;
    public class Test {
    public static void main(String args[]) {
    String cmd[] = {"java", "-version"};
    Runtime runtime = Runtime.getRuntime();
    try{
    Process proc = runtime.exec(cmd);
    }catch(Exception ioException){
    ioException.printStackTrace();
    /* Program ends here */
    There is neither any exception nor any result.
    The result I am expecting is it should print the following:
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
    Please help me out in this regard
    Thanks in advance
    Chotu.

    Yes your right. It is proc.getInputStream() or proc.getErrorStream(). That is what I get for trying to use my memory instead of looking it up. Though hopefully the OP would have seen the return type of the other methods and figured it out.

  • Can i develope a java application using C API

    hai,
    i have C api, the project was developed in C before, now i am having that api. I have to do that in java by using that C api.
    can any one suggest me how to do this?

    Your question is not that very clear!! You want to convert the C api to a Java api? or you want to develop a Java application that uses the C api?
    For the first question I believe that you should check the functionality of the C api and re-code it in Java! do not believe you should find anything imposible in that! (unless that api is trying to do something crzy directly with memory)
    For the second question then I believe you will have to use native calling or something like that. I have never used it, but read about it, and it seems one way how Java can interect with C.
    Over here there is a forum.
    Regards,
    Sim085

  • How can I run a Java-Application with a Desktop-Icon ?

    Hello,
    I have got a problem: I want my Java-application directly by clicking on a desktop icon. Is there anybody who can tell me how to do so ? (I don't want to change my application into an exe File !!!).
    It would be nice if you could give me a detailed explanation (or a link to thus) because I'm not used to the Windows-Classpath System (...as far as I need this...I don't know).
    Thank you very much,
    Findus

    Ok...in the syntax just postet I forgot to set the absolute path of the file...but eveb if I do so it does not work...here the variations I tried...
    D:\j2sdk1.4.1_01\bin>java D:\Viever\Gui
    Exception in thread "main" java.lang.NoClassDefFoundError: D:\Viever\Gui
    D:\j2sdk1.4.1_01\bin>java D:/Viewer/Gui
    Exception in thread "main" java.lang.NoClassDefFoundError: D:/Viewer/Gui
    D:\j2sdk1.4.1_01\bin>java D:\Viewer\Gui.class
    Exception in thread "main" java.lang.NoClassDefFoundError: D:\Viewer\Gui/class
    D:\j2sdk1.4.1_01\bin>java D:Viewer/Gui
    Exception in thread "main" java.lang.NoClassDefFoundError: D:Viewer/Gui

  • Invoking "java myClass" using Runtime.Exec from a Java Stored Procedure

    Hi All,
    This is regarding the use of Runtime.getRunTime().exec, from a java programme (a Java Stored Procedure), to invoke another Java Class in command prompt.
    I have read many threads here where people have been successuful in invoking OS calls, like any .exe file or batch file etc, from withing Java using the Runtime object.
    Even i have tried a sample java programme from where i can invoke notepad.exe.
    But i want to invoke another command prompt and run a java class, basically in this format:
    {"cmd.exe","java myClass"}.
    When i run my java programme (in command prompt), it doesnt invoke another command prompt...it just stays hanging.
    When i run the java programme from my IDE, VisualCafe, it does open up a command prompt, but doesnt get the second command "java myCLass".
    Infact on the title of the command prompt (the blue frame), shows the path of the java.exe of the Visual Cafe.
    and anyway, it doesnt run my java class, that i have specified inside the programme.
    Even if i try to run a JAR file, it still doesnt do anything.
    (the JAR file other wise runs fine when i manually invoke it from the command prompt).
    Well, my question is, actually i want to do this from a Java Stored Procedure inside oracle 8.1.7.
    My feeling is, since the Java Stored Procedure wont be running from the command prompt (i will be actually invoking it through a Oracle trigger), it may be able to invoke the command prompt and run the java class i want. and that java class has to run with the SUn's Java, not Oracle JAva.
    Does any one have any idea about it?
    Has anyone ever invoked a java class or JAR file in command prompt from another Java Programme?
    YOur help will be highly appreciated.
    (P:S- Right now, my database is being upgraded, so i havent actually been able to create a Java Stored procedure and test it. But i have tested from a normal java programme running in command prompt and also from Visual Cafe).
    Thanks in advance.
    -- Subhasree.

    Hello Hari,
    Thanks for your quick reply.
    Can you please elaborate a little more on exactly how you did? may be just copy an dpaste taht part of teh code here?
    Thanks a lot in advance.
    --Subhasree                                                                                                                                                                                                                                                                                                                                                                                                           

  • Running jar in unix using runtime exec command

    Hi, i want to run a jar in unix with the runtime.exec() command,
    but i couldn't manage to do it
    Here is the code
    dene = new String[] {"command","pwd","java tr.com.meteksan.pdocs.pdf.html2pdf "+ f.getAbsolutePath() + " " + pdfPath};
              System.out.println("Creating PDF");
              FileOutputStream fos = new FileOutputStream(new File(pdfPath));
              Runtime rt = Runtime.getRuntime();
              for(int i = 0 ; i < dene.length ; i++)
                  System.out.println("komut = "+dene);
              Process proc = rt.exec(dene);
              // any error message?
              StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // any output?
              StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", fos); // kick them off
              errorGobbler.start();
              outputGobbler.start();
              // any error???
              int exitVal = proc.waitFor();
              System.out.println("ExitValue: " + exitVal);
              fos.flush();
              fos.close();
    when i run this program, the exit value of the process is 0
    can you tell me whats wrong?

    i changed the string to be executed to:
                             dene = new String[] {"sh","-c","java -classpath \"" + Sabit.PDF_TOOL_PATH
                                  + "avalon-framework-4.2.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "batik-all-1.6.jar:" + Sabit.PDF_TOOL_PATH
                                  + "commons-io-1.1.jar:" + Sabit.PDF_TOOL_PATH
                                  + "commons-logging-1.0.4.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "fop.jar:" + Sabit.PDF_TOOL_PATH + "serializer-2.7.0.jar:"
                                  + Sabit.PDF_TOOL_PATH + "Tidy.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xalan-2.7.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "xercesImpl-2.7.1.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xml-apis-1.3.02.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xmlgraphics-commons-1.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "html2pdf.jar:\" tr.com.meteksan.pdocs.pdf.html2pdf "
                                  + f.getAbsolutePath() + " " + pdfPath};     
    and it works now ;)
    thanks...

  • Start a new java process using Runtime.Exec() seems to ignore the -Xmx

    I am working with a process that requires a minimum of 1.5 GB to run and works better if more is available.
    So I am determining how much memory is available at startup and restarting the jre by calling
    Runtime.exec("java -Dcom.sun.management.jmxremote=true -Xmx1500M -jar XXX.jar")
    which reinvokes the same process with a new max memory size.
    The initial call to the process is
    java -Dcom.sun.management.jmxremote=true -Xmx3500M -jar XXX.jar
    The initial call returns 3262251008 from Runtime.maxmemory()
    When reinvoked through Runtime.exec() as above
    Runtime.maxmemory() still returns 3262251008
    Is there a way to separate the new process from the size specified by the parent process?

    That is strange. Here is a program I wrote which calls itself recursively.
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    import java.util.ArrayList;
    import static java.util.Arrays.asList;
    public class MemorySize {
        public static void main(String... args) throws IOException, InterruptedException {
            System.out.println("Maximum memory size= "+Runtime.getRuntime().maxMemory());
            if (args.length == 0) return;
            List<String> cmd = new ArrayList<String>();
            cmd.add("java");
            cmd.add("-cp");
            cmd.add(System.getProperty("java.class.path"));
            cmd.add("-Xmx"+args[0]+'m');
            cmd.add("MemorySize");
            cmd.addAll(asList(args).subList(1,args.length));
            Process p = new ProcessBuilder(cmd).start();
            readin(p.getErrorStream());
            readin(p.getInputStream());
        private static void readin(final InputStream in) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        byte[] bytes = new byte[1024];
                        int len;
                        while((len = in.read(bytes))>0)
                            System.out.write(bytes, 0, len);
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
            }).start();
    }If you run this with the args 128 96 33 222 it prints out
    Maximum memory size= 66650112
    Maximum memory size= 133234688
    Maximum memory size= 99942400
    Maximum memory size= 35389440
    Maximum memory size= 231014400

  • How can i run my java Application stand alone?

    Dear all,
    As the topic i want to run my application in a single file without showing the dos prompt or type in the command in dos prompt by the user......
    How can i do that, since in my application , i have used so other package?
    In fact i just want to do something like just run a executable file in windows.
    Thx

    Sounds like your JRE didn't install properly. Either reinstall it or you can enter the file association manually.
    On Windows NT (it may be different on other versions of Windows) take the View/Options menu item from an Explorer window
    Click on the File Types tab.
    Click the "New Type" button.
    Give it the name "Executable jar file" and an associated extension of jar
    Click the "New.." button
    Make the action open
    Make the application something like
    "C:\Program Files\Java\j2re1.4.0\bin\javaw.exe" -jar "%1"
    changing it for your installation.
    Col

  • How  can I start my Java Application using double-click  in Windows XP?

    I hava developed an editor in java. The file made by this editor is saved as the .cte format. so, I need to associate this file with the editor, which means that when you double click the .cte file ,this file will be opened in the editor just like the notepad.
    I know that Jbuider has used the JNI to achieve this way to open a project. So, will you kindly tell me the details about this technique or give me some document? My E_Mail is [email protected]
    Best Regards,
    Maria

    I think this can be done from a batch file which you can execute when you install your application.
    There are two commands which you are interested in, and they are:
    assoc - Displays or modifies file extension associations.
    ftype - Displays or modifies file types used in file extension associations.
    You should use assoc to associate an extension with a file type, and ftype to associate the file type with an application.
    E.g. jar is associated with this on my machine:
    .jar=jarfile (from assoc)
    jarfile="C:\Program Files\Java\jre1.5.0_06\bin\javaw.exe" -jar "%1" %* (from ftype)
    Kaj

Maybe you are looking for

  • Make a router out of a simple notebook with one NIC (buy a second NIC)

    Hello all, Before starting, I think I must say hello to you because I'm new here : this is my first post . So, in fact, I'm working with Linux since 5 years. I'm running Gentoo on my workstation and my old server, Ubuntu on my notebook and for family

  • Menu not looping and titles not showing up

    Hello, I made some dvd\s which looked good before i send them to the guy who duplicates them for me and he noticed some issues i cannot figure out. If i could get some help or directions that would be great. i have included screen shots below the que

  • Remove movie from button

    Hello, How can you unlink a movie from a button without using undo?

  • Programs for SAPScripts

    Team, I am looking for a report or a table that lists all my Z-Forms (Custom forms) and the programs for these forms. I have looked at table TTXFP. But there are still some more forms I did not see in the table. I was wondering if there are any more

  • Payload empty in creating form (wizard)

    Hi I have a proces that uses objects from the business catalog in order to build a human task worklist screen. After generated the taskform the first time successfully I updated some fields in the used data objects. After the update I tried to re-gen