Run external programs using runtime class

Okay, I'm experiencing a really annoying problem with java.lang.runtime
I'm building a GUI that needs to run some external programs, via a button say. These generally produce a text file or something, so I don't need to stream the output or anything (at least I'm assuming I don't?). Should be very simple...
So at the terminal (bash) I would type ./programName , and everything will run hunkey dorey.
In my code then, natrurally, I write
String cmd = "./programName";
Process p = runtime.getRuntime().exec(cmd);
But low and behold...nothing happens. What is going on here, and how do I get around it! ??
(On windows incidentally, it's no problem at all and works absolutely fine. But when I go over to mac, which is what I need to use, I'm screwed - only adding to the annoyance!)
Any help would be much appreciated as I have a deadline looming!!

You need to read the 4 sections of [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html] and implement the recommendations. Failure to implement all the recommendations will cause you grief.
P.S. The fragment of code you have posted shows that you have fallen for at least 4 of the traps.

Similar Messages

  • 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

  • Running external program using java

    hi
    i am trying to run an external program using the runtime.exec() method. my problem is that the external program only runs when i press ctrl-c to exit my program. does anyone know how i can execute the external program while my program is still running without having to quit the program?should i be using threads?
    thanks

    As per the api doc exec will be executed as a seperate process
    Process exec(String command) ------Executes the specified string command in a separate process.
    Can you able to share that code what you have written ?

  • Trying to run external script using Runtime.exec

    Hey,
    I am trying to use Runtime.exec(cmd, evnp, dir) to execute a fortran program and get back its output, however it seems to always be hanging. Here is my code snippet :
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName > inputFile.txt" , null, new File("/home/myRunDir/"));
                InputStream stream = new InputStream(process.getInputStream());
                InputStream error = new InputStreamr(process.getErrorStream());
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stream));
                BufferedReader erroutReader = new BufferedReader(new InputStreamReader(error));
                System.out.println(stream.available());  //returns 0
                System.out.println(error.available());     //returns 0
                while (true) {
                    String line1 = stdoutReader.readLine();  //hangs here
                    String line2 = erroutReader.readLine();
                    if (line1 == null) {
                        break;
                    System.out.println(line1);
                    System.out.println(line2);
                }I know for a fact that this fortran code prints out stuff when run it in terminal, but I don't know if I have even set up my Runtime.exec statement properly. I think I am clearing out my error and input streams with the whole reader.readLine bit I have above, but I am not sure. If you replace the command with something like "echo helloWorld" or "pwd", it prints out everything properly. I also am fairly confident that I have no environmental variables that are used in the fortran code, as I received it from another computer and haven't set up any in my bash profile.
    Any Ideas?

    Okay, so I implemented the changes from that website (thanks by the way for that link, it helps me understand this a little better). However, my problem is still occuring. Here is my new code:
                class StreamThread extends Thread {
                InputStream is;
                String type;
                StreamThread(InputStream is, String type)
                    this.is = is;
                    this.type = type;
                public void run()
                    try
                        InputStreamReader isr = new InputStreamReader(is); //never gets called
                        BufferedReader br = new BufferedReader(isr);
                        String line=null;
                        while ( (line = br.readLine()) != null)
                            System.out.println(type  +">"+  line);
                        } catch (IOException ioe)
                            ioe.printStackTrace();
            try {
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName" , null, new File("/home/myRunDir/"));
                StreamThread stream = new StreamThread(process.getInputStream(), "OUTPUT");
                StreamThread errorStream = new StreamThread(process.getInputStream(), "ERROR");
                stream.start();
                errorStream.start();
                int exitVal = process.waitFor(); //hangs here
                System.out.println("ExitValue: " + exitVal);

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

  • Compile and run java programs using batch file

    i am using eclipse to run my java programs.How to compile and run those programs using a batch file?

    a) just write a batch file, and add it to the project. When you want to run it, go to a command window and invoke it. (There is probably also a way to invoke it from Eclipse)
    b) if the project is complicated, take a look at ant. Eclispe knows about ant files.

  • 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

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

  • Running External Program

    Hi All
    I really hope that some one can help ,e with my problem as i have no idea. OK i am calling an external program that outputs documents. This program uses control files and for each job there are 5 control files. Thus i call this program 5 times to get all my output documents. When i run this program from the command line then it works fine, however when i call it from my code i can see that it is working because my outputs are processed and i can see the program in the task manager. But it stops and does not continue to the next call, its like after this program does the processing then it just hangs. I dont know what is wrong and i cant get any errors in the logs either. I think that the problem either is with my java instalation as i had problems on the server and had to re-install java because someone installed multiple versions or that it is a jvm problem. Can some one please give some ideas of what could be the problem. My code looks as follow:
    Process p = Runtime.getRuntime().exec("d://cep//nt_engine_010_62 prodengine -controlfile=d://cep//document1.txt");
    p.waitFor();
    System.out.println(p.exitValue());

    You may want to give this code a try:
    ProcessBuilder pb = new ProcessBuilder( whatever_command );
          pb.redirectErrorStream();
          Process p = pb.start();
          InputStream is = p.getInputStream();
          BufferedReader br= new BufferedReader( new InputStreamReader( is ) );
          for ( String line = br.readLine(); line != null; line = br.readLine() )
            System.out.println( line );
          p.waitFor();

  • Run external programs

    Hi there..
    I need a example to run others programs from Java, for example lunch the explorer.. Is possible do that?
    Thanks you

    Have a look at the Runtime class and especially the exec method. You should be able to do what you want using the following code:
    Runtime.getRuntime().exec("explorer");

  • Unable to run Servlet program using J2EE SDK

    Hello,
    i am a newbie to all this j2ee stuff and servlets even.so the problem that i have maybe a very common one and i hope that most of you may have a fix to it...
    i use J2EE SDK to compile and run Servlet programs.I have a Servlet program with the class name defined as
    public class MyServlet extends HttpServlet ....
    the file is stored as MyServlet.java
    i set the CLASSPATH variable so that the required classes for the compilation of the program can be located.
    the program compiles without any glitches.
    However when i run the program by saying
    java MyServlet
    ( i dont think its any different to run servlet code is it?)
    i get the message
    java.lang.NoClassDefFoundException:MyServlet
    Can someone suggest a remedy?
    thank you
    -NDK

    First, I don't understand what you are trying to do. Running a servlet ?
    Servlets are ran by an application server ! (Apache Tomcat ....).
    Second, is your class in any package ?

  • How to run the program using specific classpath

    Recently I installed Javamail 1.2 and JAF1.0.1 on my NT Box and set up the classpath. I can compile my java email code by using: javac myEmail.java. But when I tried to run the code using java myEmail, it always gives the error: Exception in thread "main" java.lang.NoClassDefFoundError: myEmail.
    when I use -verbose and found that it always goes to:
    C:\Program Files\JavaSoft\JRE\1.3.1\lib\rt.jar to find classes even I use -cp option to point Javamail\mail.jar and activation.jar.
    what is wrong with it? Thank you in advance!!!!!!

    What does this have to do with JMS. I suggest that this should have been posted to the Java Programming forum where you would have gotten a quick response as this is a simple problem to diagnose.
    The problem is that the class myEmail, which you created, is not on the class path so it cannot find it. It has nothing to do with the location of mail.jar and activation.jar, although this may cause problems later.
    What you need to do is check the classpath in the environment variables section of the System dialog box. Make sure it refers to . (the current directory) as well as the locations of mail.jar and activation.jar. Also when you invoke myEmail ensure you are in the same directory.
    Hope this helps

  • AIR 2.6: Run external programs sequential (1 by 1)?

    Hi,
    I managed to run an external program in Adobe AIR (2.6). I'm using the NativeProcess for this. I would like to perform the following actions.
    Pseudo-code:
    execute program.exe
    this will return a port number
    set the port number as an environment variable (in windows)
    execute program.exe with several queries
    stop progam.exe
    The corresponding executables:
    C:\my_proj\program.exe start
    var portnumber:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
    C:\WINDOWS\system32\cmd /c set port=portnumber
    C:\my_proj\program.exe query test1
    C:\my_proj\program.exe query test2
    C:\my_proj\program.exe stop
    My problem is the bold text in my source code underneath. I'm trying to wait till the first native process is finished and had returned its output. Once I have this output (=the portnumber) I can continue with the following action. And this is needed for all steps ... to execute them one by one.
    But "do {} while (process.running);" is not working. My AIR applications is getting stuck in this loop ... as if process.running is always true.
    Any idea how I can execute external programs sequential?
    This is my source code:
                var file:File = File.applicationDirectory;
                file = file.resolvePath("NativeApps");
                if (Capabilities.os.toLowerCase().indexOf("win") > -1)
                    file = file.resolvePath("C:\\my_proj\\program.exe");
                var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
                nativeProcessStartupInfo.executable = file;
                var processArgs:Vector.<String> = new Vector.<String>();
                processArgs[0] = "start";
                nativeProcessStartupInfo.arguments = processArgs;
                nativeProcessStartupInfo.workingDirectory = File.documentsDirectory;
                var process:NativeProcess = new NativeProcess();
                process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
                process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
                process.addEventListener(NativeProcessExitEvent.EXIT, onExit);
                process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
                process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
                process.start(nativeProcessStartupInfo);
                do {} while (process.running);
                file = file.resolvePath("NativeApps");
                file = file.resolvePath("C:\\WINDOWS\system32\\cmd");
                var nativeProcessStartupInfo2:NativeProcessStartupInfo = new NativeProcessStartupInfo();
                nativeProcessStartupInfo2.executable = file;
                processArgs[0] = "/c";
                processArgs[1] = "set";
                processArgs[2] = "port="+portnumber;
    public function onOutputData(event:ProgressEvent):void
                var process:NativeProcess = event.target as NativeProcess;
                var portnumber:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
    public function onExit(event:NativeProcessExitEvent):void
                process.exit();

    Hello,
    The  "do {} while (process.running);" may take almost all of the resource, so other code was blocked, then the program seems no response.
    You can add the following code in the onOutputData, like:
    public function onOutputData(event:ProgressEvent):void
        var process:NativeProcess = event.target as NativeProcess;
        var portnumber:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvail able);
        file = file.resolvePath("NativeApps");
        file = file.resolvePath("C:\\WINDOWS\system32\\cmd");
        var nativeProcessStartupInfo2:NativeProcessStartupInfo = new NativeProcessStartupInfo();
        nativeProcessStartupInfo2.executable = file;
        processArgs[0] = "/c";
        processArgs[1] = "set";
        processArgs[2] = "port="+portnumber;

Maybe you are looking for

  • Is it possible to force only a single evaluation of a function?

    I am only an occasional user of numbers... The question:  Is it possible to force a single evaluation of a function like TODAY() ? i wanted to place the current date into a gas milage numbers document, and I foolishly used =Today(). Well the second t

  • Output from JDBC Adapter mapped to multiple message types

    Hi! I face to a problem with the message mapping.. I do select with the JDBC adapter. This statement selects one field of clob type and it already contains a message - XML document. Depending of the type of this message will be done the message mappi

  • Dynamic front panel

    Hi, I'm working on a VI that will be used to control a number of RC Quadcopters and cars. The VI gets the amount of vehicles from tracking tools, and then runs a loop and finds out for each vehicle if it's a quad or a car. Now that that stage is comp

  • My calendar will not show invites from others

    When I am sent an appointment invite and I accept it it does not show up in my calendar.  It use to a few months ago.  I have MacBook Pro adn IPad as well and they don't show up on any of the devices.

  • What is VB6's EventParameters in C#

    Hi, What is VB6's EventParameters equivalent class/method in .NET framework? and how to get the event's parameters in C#. Thanks,