Runtime classes method exec

What is the purpose of exec(String cmd[ ],String env[ ],File) method in the Runtime class of lang package and can I give more than one command in the first string and will they be executed?Plz help

What is the purpose of exec(String cmd[ ],String
env[ ],File) method in the Runtime class of lang
package and can I give more than one command in the
first string and will they be executed?Plz helpTo try to give a detailed explanation as a response would take pages and pages. A lot of this is covered in http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html so give this a read, then a second read and then come back.
You need to say what you mean by 'more than one command'. Do you mean 'more than one command on the command line' or do you mean 'more than one command passed to the stdin of some command processor' ? Either way, you need to specify the operating system you are using and the sort of commands you want to use.

Similar Messages

  • Problem with Runtime,process method exec and jar

    I have a application in java and it execute a executable C with method exec.
    It work well. But when I make the jar file, I have the exucatable inside of jar, but I don't know like I have to write the executable's path in the method exec(".......")
    thank you and sorry for my english

    You can't. You have to use the zip mechanism and extract it before using it.

  • Runtime class exec statement

    I would like to know why while using a Runtime class object with exec method it is able to execute certain commands where as it is not able to do certain other. Like Procees p, Runtime r and p=r.exec("notepad abc.dat" works and p=r.exec("java abc") doesnot work.the path has been set also. How can one call other java programs to be executed from one program? are there other ways. tried jexepack with a very limited success.

    Here's one way of doing it albeit not via the Runtime path - here you just need to provide the class which needs to be invoked as value of variable 'className'. This by default runs the class with no arguements to main - if you wish to provide some args then do so in variable 'argListForInvokedMain'
    String className = "a";
    try {
    Class[] cls = new Class[1];
    cls[0] = String[].class;
    Method mainMethod = Class.forName(className).getDeclaredMethod("main",cls);
    Object[] argListForInvokedMain = new Object[1];
    argListForInvokedMain[0] = new String[0];
    //put arguements in here
    mainMethod.invoke(null,
    argListForInvokedMain);
    catch (ClassNotFoundException ex) {
    System.out.println("Class "+ className +" not found in classpath.");
    catch (NoSuchMethodException ex) {
    System.out.println("Class "+ className +" does not define public static void main(String[])");
    catch (InvocationTargetException ex) {
    System.out.println("Exception while executing "+ className +":"+ex.getTargetException());
    catch (IllegalAccessException ex) {
    System.out.println("main(String[]) in class "+ className +" is not public");
    Hope this helps
    John Morrison

  • Runtime class

    i am trying to execute an exe file made from a c++ program from my java code....
    i am using the runtime class and the exec method....
    but since c++ programs dont run in JRE environment....the exe file is not getting executed...
    what shud i do?
    plz help.....

    What do you make after this lines.
    Could be useful to wait for that process:
    p.waitFor();
    By default the process uses the null device to print out message.
    That means you get no message output.
    Use the getInputStream() and getErrorStream() to pipe the output into your application and to print out
    the message to System.out or System.error
    Why do you think that your c-application is not running?
    Do you get an exception?
    It also possible that you have to make the Porcess object more global, so that the garbage collector
    doesn't destory the object while executing c-application.
    regards
    Andy

  • BCP data into a file using Runtime class

    Hi,
         I have a problem in using the Runtime class.
    I am trying to bcp a table's data into a file.I am working on a Unix environment.
    My bcp is not getting completed fully.The total records to be bcped is 1 million,but only one lakh records is getting bcped and then it hangs up..But if i issue the bcp command from my telnet session it is bcping it to the file without any problem.Can anyone help me out on how to overcome this..
    Is there anything specific with Runtime class..I am pasting the code that i tried out below.
    String l_s_bcpQuery="bcp mubstage.dbo.HousingUnitSampleMarket out /dun/d3nmb0/mariaps/subracheckprototype -c -t~ -Umariaps -Prykwz5ba -SD3NMB_MUB";
    try{
    Runtime time=Runtime.getRuntime();
    Process p=time.exec(l_s_bcpQuery);
    p.waitFor();
    System.out.println("The exit value is:"+p.exitValue());
    }catch(Exception ioe){
         ioe.printStackTrace();
         System.out.println("IOException"+ioe.getMessage());

    you might need to capture the stout & sterr from the process. see http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Process.html, or many other similar questions on this forum.
    try this:
    try{
    Runtime time=Runtime.getRuntime();
    Process p=time.exec(l_s_bcpQuery);
    BufferedReader stout = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader sterr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    String out = stout.readLine();
    String err = sterr.readLine();
    while((out != null)||(err != null))
    if(out != null)
    System.out.println(out);
    if(err != null)
    System.err.println(err);
    out = stout.readLine();
    err = sterr.readLine();
    int exit_value = p.waitFor();
    System.out.println("The exit value is:"+ exit_value);
    }catch(Exception ioe){
    ioe.printStackTrace();
    System.out.println("IOException"+ioe.getMessage());
    }

  • Executing a command using Runtime Class

    How to execute a command on a differnet machine with different ipaddress using Runtime Class
    My code is
    String[] cmd = new String[3];
    cmd[0] = "192.1...../c:/WINNT/system32/cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + cmd[0] + " " + cmd[1]
    + " " + cmd[2]);
    Process proc = rt.exec(cmd);
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    This is not Working

    I have same issue. Actually when I use cmd.exe /c set in java code and if I run the java code in DOS propmt, it retrieves all latest user Environment variable values. But if I run the code in windows batch file, it is not retrieveing the latest user environment values until I reboot my computer, Do you know how to get user environment value with out rebooting machine??????

  • FTP using Runtime class ...Please Help ??

    Hi,
    I am trying to ftp a file programatically.
    I am trying to use Runtime class but facing problems
    in it.This is what I am trying to do :
    Runtime rr = Runtime.getRuntime();
    String[] cmds = new String[2];
    cmds[0]="username=rahmed";
    cmds[1]="password=prpas";
    try{
    Process p = rr.exec("ftp 192.168.1.18",cmds);     
    rr.exec("put vv.txt");
    This does not work ??
    Is there any way to make it work ? Or is there any
    other way to ftp a file programatically ??
    Thanks in adavance..
    Regards
    Rais

    Under Linux/Unix at least, it is good to use the switches -n and -i with the ftp client acually meant for intercative usage.
    -i Turns off interactive prompting during multiple file transfers.
    -n Restrains ftp from attempting ``auto-login'' upon initial connection.
    I do "user <myuser> <mypassword>" then from the script.
    I am happily using ftp this way from shell-scripts in my projects.
    scp is however better than ftp: it does not send plain text passwords over the net, it support key-based login, its encrypts the data.

  • Invoking Derived Class Method

    Hi pls go through the below code, can any one give me solution how to access the Derived class method in this Point.
    Note: In the below code , only in runtime we will come to know which Derived class method is going to invoke(So in runtime we will get Derived class name in the form of String). So Iam trying to Use Class.forName("Clas name") to create the instance of the Derived class and then type casting to base class.
    Why iam casting to base class is , since only in the run time we are geting the Derived class name.
    Result : iam geting the compiletime error says that no valid method fond in Mybase though it contains the reference of derived.
    abstract class MyBase
    public void display(int i)
    System.out.println(" Base class Method");
    class MyDerived extends MyBase
    public void display(String str)
    System.out.println("Derived class Mthode");
    class MyMain
    public static void main(String arg[])
    String DrivObj=arg[0];
    MyBase baseObj=(MyBase) Class.forName("DrivObj").newInstance();
    baseObj.display("SomeString"); }
    }

    The problem is, can not have subclass reference bcoz
    iam geting the subclass name only in the runtime and
    one more thing is cant touch my base and subclass to
    do changes as u said Your design is then definately very bad.
    , is there any other way to do
    it.Yes, you can use reflection to invoke the method.
    Kaj

  • Using Runtime class

    Hi,
    i would like to run a an external java program from within another java program,
    here is the structure of my called parogram
    c:/temp/jetty
    /lib/*.jar
    start.jar
    my caller program have to invoke the start.jar, but this jar uses the lib folder
    so my code construct a java command with the -cp options giving all the jar, and finally use th runtime class to call start.jar
    here is the code :
    String command = "java -cp D:/temp/jetty/lib/jetty-6.1.0.jar;D:/temp/jetty/lib/etc/another.jar -jar D:/temp/jetty/lib/jetty-6.1.0/start.jar"
    Runtime runtime = Runtime.getRuntime();     
    runtime.exec(command);
    it doesnt work, (classnot found error!!!) evenif i include in the cp option all the jar,
    my question is how to force the runtime to start the execution at c:/temp/jetty ??
    can anyone help

    Try this for ideas
    package testing;
    import java.io.IOException;
    public class Test
      public static void main(String[] args) throws IOException
        Runtime.getRuntime().exec("java -jar AnotherJar.jar");
    }and
    package testing;
    import javax.swing.JOptionPane;
    public class Another
      public static void main(String[] args)
         JOptionPane.showMessageDialog(null, "Another .jar running", "Blaa blaa", JOptionPane.INFORMATION_MESSAGE);
    }Then compile both, create manifests for both, create the jars (name the .jar corresponding to class Another as AnotherJar.jar), put the jars in the same directory and run the .jar that corrsponds to class Test.
    edit
    And obviously, in your case, you need to add the line
    Class-Path: lib/*.jar
    to the manifest of the program that needs the jar in directory lib.
    Message was edited by:
    duckbill

  • Java programming - Runtime class

    hi
    I am not able to copy a file using Runtime class in java.lang
    i have used
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("copy c:/venk1/pmrpay.jar F:/");
    pr.waitFor();
    when running the program i am getting this error message:
    create process: copy c:/venk1/pmrpay.jar F:/ error = 2
    kindly help me
    venkat

    There is no copy.exe on your system. Copy is command interpreted with command.com. So you need to try something like
    Process pr = rt.exec("cmd /c copy c:/venk1/pmrpay.jar F:/");
    See
    cmd /?
    for details... Hope this will help you!

  • Get runtime class and cast object to it?

    Hi,
    public interface Msg
    Msg msg=msgLib.get(msgType);
    Msg msg2=msg.clone(); //problem! cannot find clone in  x.y.Msg!
    ...Shouldn't msg be resolved to the implementing class (MsgReply for example) and use the "clone()" method, that i have declared in that class -which overrides the one of Object class?
    If no, is there a way to find the runtime class -probably use "getClass"- and cast to it? How?
    Thanks

    There are many implementing classes; i want to get the runtime class. Something like:
    (msg.getClass())msg.clone();
    Message was edited by:
    uig

  • Unable to start Tomcat using runtime class in windows 98

    hi,
    I am using a runtime class which calls a batch file, that calls statup.bat for starting tomcat.
    This works perfectly in windows NT,2k. But on win 98, the tomcat window opens and closes within no sometime.
    In my class i call the first batch file starter.bat using
    Runtime.getRuntime().exec("%COMSPEC% /c start e:/starter.bat");
    (I tried with command.com also...)
    Starter.bat has the line
    call E:\jakarta-tomcat4.1\bin\startup.bat.
    Is there anyother way to start the tomcat process and keep it running on windows 98. Anyone with anyclues pls help.
    Thanks in advance.

    This is the Runtime class i am using... Sometimes tomcat gets closed and sometimes just hangs... (putting it in for better understanding..)
    public class Starter {
         public static void main(String[] args) {
              String com = "%COMSPEC% /c start
    C:\\PACS\\SFAApp\\tomcat\\startup.bat";
                   try     {               
                        Runtime rt = Runtime.getRuntime();
                        Process pr = rt.exec (com);//Starting tomcat
                        try
                             pr.waitFor();     
                        catch (Exception e)
                             e.printStackTrace();
                   catch (IOException ie) {
                        System.out.println("IOException caught" + ie);
                        ie.printStackTrace();

  • Runtime class behaving erratic

    hi all,
    I am writing a simple network shell in java...it runs well for any dos commands but it doesn't executes a .exe file (using runtime class) while the program is active but when i quit the program the .exe file called before runs.
    what's the problem...

                            else if(array.length == 2 && array[1] == ':'&& array[2] == '\\')
                                   for (int index = 0; index < roots.length; index++)
                                        if(string1.equals(roots[index].toString()))
                                            System.setProperty("user.dir", string1);
                                            pwd = System.getProperty("user.dir");
                                            output.println(pwd);
                                            output.flush();
                            else if(array[0] == 'c' && array[1] == 'd' && array.length > 2)
                                       System.setProperty("user.dir", string1.substring(3));
                                //System.out.println(string1.substring(3));
                                pwd = System.getProperty("user.dir");
                                output.println(pwd);
                                //output.flush();
                            else if(string1.endsWith(".exe") || string1.endsWith(".avi"))
                                System.out.println(pwd+"\\"+string1);
                                       String run1 = pwd+"\\"+string1;
                                       /* Thread t = new Thread(new Run(run1));
                                       t.start(); */
                                       rtime.exec(run1);////******* HERE LIES THE PROBLEM @run1 path of the .exe file
                                       continue;
                                  else
                                       commands[2] = string1;
                                p = rtime.exec(commands);                           
                                Scanner scan = new Scanner(p.getInputStream());
                                       String out = "";
                                while(scan.hasNextLine())
                                            out = out + scan.nextLine()+"~";
                                            //output.flush();
                                output.println(out);
                                       output.flush();
                                  output.println("end");
                                  output.flush();
            catch (IOException ex)
                ex.printStackTrace();
         public void run()
              try
                   Runtime.getRuntime().exec(string);
              catch(IOException e)
        private static DatagramSocket clientSocket;
         private static MulticastSocket multiSocket;
        private static int boundPort = 8000;
        private static int multiPort = 5678;
         private static InetAddress group;
         private static String string = "active";
        private static String pwd;
         private static PrintWriter output;
        private static Scanner input;
        private static Process p;
        private static DatagramPacket packet;
    }

  • Runtime class (with scp command)

    Hello
    I wrote a working code , but I think there may be a simpler way to do it.
    I would like to know if it's possible to use the Runtime class , to connect to a remote server and download a file to my computer, using scp command .
    something like:
    String command = "scp Username@server : fileWanted destinationPath";
                Runtime runtime = Runtime.getRuntime();
                Process child = runtime.exec(command);Something in this manner(obviously I will need to take care of the password issue).
    (A code sample will be great)
    thanks,Dave

    You might be interested in jsch, Java Secure Channel (BSD license), a pure-Java implementation of SSH2:
    http://www.jcraft.com/jsch/index.html
    See "ScpFrom.java" in "examples" directory.

  • Help with Runtime class and timeout of Process

    Hi,
    Question regarding using Runtime class, and yes I have looked at the javadocs, but I am still confused and frustrated.
    Here is part of my code.
    Process p;
    Runtime runtime = Runtime.getRuntime();
    p = runtime.exec("rsh localhost ls");
    if you are not familiar with rsh all it does is remote shell into the computer localhost and executes the command ls.
    Now, I dont have rsh running on my computer so it will hang at that line for about 40 sec and eventually time out on its own. Is there anyway I can specify a timeout argument like there is for the ping command? Like if there is no response from localhost after 3 sec, then just kill the process?
    I looked at the Runtime javadoc and Process javadoc and the closest thing I could come to with is something to do with envp (environment parameters), but I dont know what that is.
    Thanks guys.

    You can't timeout the "runtime.exec("rsh localhost ls");" call but if you execute the call in a seperate thread you can "timeout" and continue executing on the original thread (while letting the "runtime" thread to timeout on its own).
    Check the following class that I created for cases like this:
    abstract public class TimeoutHelper implements Runnable
        private Throwable error;
        private boolean running = true;
        private Object retValue;
        protected String name;
        private long waitTime;
        private Thread thread;
         * Creates a new helper. Use {@link #start} to run the code.
         * @param name A name that will be used in the helper thread name
         * @param waitTime The time (in msec) to wait before timeout.
        public TimeoutHelper(String name, long waitTime)
            this.name = name;
            this.waitTime = waitTime;
        public Object start() throws Throwable
            return asyncExecute();
        abstract protected Object execute() throws Throwable;
        private synchronized Object asyncExecute() throws Throwable
            createThread().start();
            if (running)
                try
                    wait(waitTime);
                    if (running)
                        // Timeout!!
                        abortThread();
                        throw new TimeOutException("Timeout for: " + name);
                catch (InterruptedException ie)
                    // Ignore
            if (error != null)
                throw error;
            return retValue;
        private void abortThread()
            if (thread != null)
                thread.interrupt();
        protected Thread createThread()
            thread = new Thread(this, name);
            return thread;
        public void run()
            try
                retValue = execute();
            catch (Throwable th)
                error = th;
            synchronized (this)
                running = false;
                notifyAll();
    }You use the class by extending it and implementing "execute". For example:
            TimeoutHelper helper = new TimeoutHelper("Runner", 5000)
                protected Object execute() throws Throwable
                    Runtime runtime = Runtime.getRuntime();
                    return runtime.exec("rsh localhost ls");
            try
                Process p = (Process)helper.start();
            catch (TimeOutException e)
                // Handle timeout here
            catch (Exception e)
                // Handle other errors here.
            }

Maybe you are looking for