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??????

Similar Messages

  • Problem to execute cvs command using Runtime.exec method

    Hello,
    I want execute this cvs command, with this options:
    cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d "2007/05/01<now" Project
    I tried to execute with Runtime.exec() :
    Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
    But I have an error because the smaller character is interpretate as a redirection, no as a smaller symbol.
    How I can do to use this command with Runtime.exec ?
    Thanks.
    Regards.

    Sorry,
    I had a typing mistake.
    I want say:
    Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
    Regards.

  • Execute an external program using Runtime class

    How to execute an external java program using Runtime class?
    I have used ,
    Process p=Runtime.getRuntime().exec("c:/j2sdk1.4.0/bin/helloworld.java ");
    But it throws a runtime IOException error:2 or error:123.
    Help me with the code. Thanks in advance.

    Create Runtime Object and attach to system process.Try this code
    import java.io.*;
    public class ExecuteExternalApp {
      public static void main(String args[]) {
                try {
                    Runtime rt = Runtime.getRuntime();
                    //Process pr = rt.exec("cmd /c dir");
                    Process pr = rt.exec("c:\\ yamessenger.exe"); //give a valid exe file
                    BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
                    String val=null;
                    while((val=input.readLine()) != null) {
                        System.out.println(val);
                    int exit = pr.waitFor();
                    System.out.println("Exited with error code "+exit);
                } catch(Exception e) {
                    System.out.println(e.toString());
                    e.printStackTrace();
    }Edited by: anishtomas on Feb 3, 2009 9:34 PM
    Edited by: anishtomas on Feb 3, 2009 9:37 PM

  • Error while Executing Unix Shell Commands Using Runtime clas

    I am trying to run the following code in java on unix machine to execute cat command.
    Runtime runtime = Runtime.getRuntime();
              try {
                   System.out.println("before catexecute");
                   Process process = runtime.exec("cat /export/home/shankerr/local.profile > /export/home/shankerr/local1.txt");
                   try {
                        if (process.waitFor() != 0) {
                        System.err.println("exit value = " +
                                  process.exitValue());
                        catch (InterruptedException e) {
                        System.err.println(e);
    But i get the following error on the console
    exit value = 2
    cat: cannot open >
    cat: cannot open /export/home/shankerr/local1.txt
    The same command if i run on unix console directly it creates a new file and copies the content into the new file local1.txt
    kindly help me on the same

    The redirection operator > along with stuff like pipe | history !$ etc. is interpreted by the shell, not by the cat program.
    When you do cat X > Ycat only sees the X. The rest is interpreted by the shell to redirect the cat program's stdout.
    However, when you Runtime.exec(), you don't have the shell, so cat sees X > Y as its arguments, and interprets them all as file names. Since there's no file named > you get the error.
    The solution is to first man cat on your system and see if it happens to have a -o or somesuch operator that lets it (rather than the shell) send its output to a file. If not, then you need to invoke a shell, and pass it cat and all of cat's args as the command to execute.
    Read the man pages for you shell of choice, but for bash, I believe you'd give Runtime.exec() something like /bin/bash -c 'cat X > Y'

  • Problem while executing a command using exec()

    I'm trying to execute a command on Unix O/S with the help of java program. For this I have used Runtime class available in java.lang. It works fine for some of the basic unix commands like 'ls','cp' but when I tried to execute command "sqlldr userid=<user>/<pwd> control=/u01/dw/snb/log/sp_shd05721_ins_stg_sqlldr.ctl" , then it's not getting executed. Please advise.

    You may be having a problem with the command path, which I don't think Runtime.exec() uses. Try specifying the full path

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

  • Error in creating a process using runtime class - please help

    Hi,
    I am experimenting with the following piece of code. I tried to run it in one windows machine and it works fine. But i tried to run it in a different windows machine i get error in creating a process. The error is attached below the code. I don't understand why i couldn't create a process with the 'exec' command in the second machine. Can anyone please help?
    CODE:
    import java.io.*;
    class test{
    public static void main(String[] args){
    try{
    Runtime r = Runtime.getRuntime();
         Process p = null;
         p= r.exec("dir");
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         System.out.println(br.readLine());
    catch(Exception e){e.printStackTrace();}
    ERROR (when run in the dos prompt):
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:63)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:550)
    at java.lang.Runtime.exec(Runtime.java:416)
    at java.lang.Runtime.exec(Runtime.java:358)
    at java.lang.Runtime.exec(Runtime.java:322)
    at test.main(test.java:16)
    thanks,
    Divya

    As much as I understand from the readings in the forums, Runtime.exec can only run commands that are in files, not native commands.
    Hmm how do I explain that again?
    Here:
    Assuming a command is an executable program
    Under the Windows operating system, many new programmers stumble upon Runtime.exec() when trying to use it for nonexecutable commands like dir and copy. Subsequently, they run into Runtime.exec()'s third pitfall. Listing 4.4 demonstrates exactly that:
    Listing 4.4 BadExecWinDir.java
    import java.util.*;
    import java.io.*;
    public class BadExecWinDir
    public static void main(String args[])
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("dir");
    InputStream stdin = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<OUTPUT>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    System.out.println("</OUTPUT>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    A run of BadExecWinDir produces:
    E:\classes\com\javaworld\jpitfalls\article2>java BadExecWinDir
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at BadExecWinDir.main(BadExecWinDir.java:12)
    As stated earlier, the error value of 2 means "file not found," which, in this case, means that the executable named dir.exe could not be found. That's because the directory command is part of the Windows command interpreter and not a separate executable. To run the Windows command interpreter, execute either command.com or cmd.exe, depending on the Windows operating system you use. Listing 4.5 runs a copy of the Windows command interpreter and then executes the user-supplied command (e.g., dir).
    Taken from:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Problem in running system commands using Runtime()

    hi,
    i am trying to run the "dir" command in windows OS using Runtime(). But while
    executing the program i am getting
    java.io.IOException: CreateProcess: dir error=2 error. But if i replace the "dir" command by "notepad" command its working fine. below is the source code.
    class testing
    public static void main(String args[])
         try{
    Runtime rt=Runtime.getRuntime();
    Process p=rt.exec("dir"); //Generating Errors
    //Process p=rt.exec("notepad"); //Working Fine
         }catch(Exception e){System.out.println(e);}
    }plzz help me out.
    thanx

    thats fine its working. i made two changes. First i used an array to send the
    arguments. if we directly use "cmd.exe /c dir" then its converting "/C" to "\C" thus
    producing the error. so i used
    Runtime rt=Runtime.getRuntime();
    String args1[]={"cmd.exe","/C","dir"};
    Process p=rt.exec(args1);But then i got no error no output. From other forums i came to know about capturing the data using input streams and i included the following code.
    BufferedReader Resultset = new BufferedReader
         (new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = Resultset.readLine()) != null)
         {          System.out.println(line);          }Now its working fine. Thanx for ur help.

  • 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());
    }

  • 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

  • Execute unix command using java

    Hello
    Can we execute a unix command using java? If it is how we can execute. Is this affect the performance of the program.
    Thanks

    I tried what you said. But its not working and returning error message,
    java.io.IOException: CreateProcess: ls -a error=2
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
    If i try this statement,
    Runtime.getRuntime().exec("c\windows\notepad");
    It is working fine.
    Any idea about this.
    Plz ...........

  • Execute SQLPLUS command using JDBC

    Hi,
    I was wondering if its possible to execute sqlplus command (eg set define off, change date format ..etc) using JDBC ?
    Can anyone please post me some sample codes about this ?
    Any help will be appreciated

    Hi,
    But the Runtime.exec() and the JDBC application have
    their own connection to the database, and the sqlplus
    commands that i need to run are session based (only
    valid during the connection). eg set define off
    How do I overcome this ?
    Huh?
    You put anything you want into a input file. You feed the input file to sqlplus. If there are results then you put them into an output file.
    None of that has anything to do with JDBC nor even with java. When you call Runtime.exec() you are running a completely different process. What you do with that process is up to you.

  • 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();

  • Getting an error while executing ddl commands using dblink

    Hi,
    i am using Oracle9iR2 Version.
    i have created a procedure like below to execute ddl commands on remote database through dblink using dbms_sql.
    CREATE OR REPLACE PROCEDURE run_remote_ddl (p_dblink VARCHAR2, qry VARCHAR2)
    AS
    c_handle NUMBER;
    feedback INTEGER;
    stat VARCHAR2 (2000);
    BEGIN
    stat := 'select DBMS_SQL.open_cursor' || p_dblink || ' from dual';
    EXECUTE IMMEDIATE stat
    INTO c_handle;
    stat :=
    'begin DBMS_SQL.parse'
    || p_dblink
    || ' ('
    || c_handle
    || ','''
    || qry
    || ''', DBMS_SQL.v7); end;';
    EXECUTE IMMEDIATE stat;
    stat :=
    ' select DBMS_SQL.EXECUTE' || p_dblink || '(' || c_handle
    || ') from dual';
    EXECUTE IMMEDIATE stat
    INTO feedback;
    stat :=
    'declare x integer; begin x:= :1; DBMS_SQL.close_cursor'
    || p_dblink
    || '(x); end;';
    EXECUTE IMMEDIATE stat
    USING c_handle;
    END;
    when i run this procedure like below
    begin
    run_remote_ddl ('@dblink', 'create table scott.ttt(num number)');
    end;
    got an error:
    ORA-06553: PLS-103: Encountered the symbol ".2" when expecting one of the following:
    . ( * @ & = - + ; < / > at in is mod not rem
    <an exponent (**)> <> or != or ~= >= <= <> and or like
    between ||
    The symbol ". was inserted before ".2" to continue.
    ORA-06512: at RUN_REMOTE_DDL", line 9
    ORA-06512: at line 2
    Please tell me how to resolve this.
    Thanks in advance.

    Hi,
    >
    ORA-06553: PLS-103: Encountered the symbol ".2" when expecting one of the following:
    . ( * @ & = - + ; < / > at in is mod not rem
    <an exponent (**)> or != or ~= >= <= <> and or like
    between
    >
    Hope you are not typing 2 instead of @ as both are on the same key
    Can you run the following and see what is happening
    CREATE OR REPLACE PROCEDURE run_remote_ddl (p_dblink VARCHAR2, qry VARCHAR2)
    AS
    c_handle NUMBER;
    feedback INTEGER;
    stat VARCHAR2 (2000);
    BEGIN
    dbms_output.put_line(p_dblink);
    stat := 'select DBMS_SQL.open_cursor@dblink from dual';
    --stat := 'select DBMS_SQL.open_cursor from dual';
    EXECUTE IMMEDIATE stat
    INTO c_handle;
    END;
    exec run_remote_ddl('@dblink', 'create table scott.ttt(num number)');Regards
    Edited by: yoonus on Feb 20, 2013 3:47 AM

  • To execute external command using   RFC_REMOTE_exec

    Hi
    i want to execute the ext command using RFC_REMOTE_EXEC .
    i have used like below in WINDOWS XP:
    data: v_cmnd(120) type C VALUE 'dir C:\SAP\rfcsdk\bin >RFEXEC -D ESM_R'.
    call function 'RFC_REMOTE_EXEC' destination D_DESTI
    exporting
    command = v_cmnd
    exceptions
    system_failure = 1 message D_ERMSG
    communication_failure = 2 message D_ERMSG.
    manually at command line the program getting registerd but
    not throuergh RFC_REMOTE_EXEC 
    in v_cmnd  what is the exact value we have to give
    Regards

    you create the command in SM69 with some name and Directly give the Same name when you are executing.
    Check this Function also.
    SXPG_COMMAND_EXECUTE

Maybe you are looking for