Runtime.exec() doesn't work

Hi all,
I have got the following piece of code, I just don't understand why I don't receive any email after I have run
the program.
public class Test {
  public static void main(String[]args) {
    Runtime.getRuntime().exec("mailx -s [email protected] < input.txt");
// where input.txt is a text file..
I know if I want to, I can you JavaMail API to make it work, but I try to avoid if I can.. please advise me..
Thanks
Regards,
Thinh

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
You need to execute a shell interpreter or manually feed the process's stdin from the file.

Similar Messages

  • Runtime.getRuntime().exec doesn't work

    I write in my program this line:
    p=Runtime.getRuntime().exec("/usr/bin/identify -verbose /tmp/cible.jpg > /tmp/cible.jpg.txt");
    But the file cible.jpg.txt is not created!
    Can you explain me?
    advance thanks!
    Best regards!!!

    It doesn't work because it is literally passing the "> /tmp..." characters as a command-line argument to the "/usr/bin/identify" program, as opposed to having the shell interpreter (which you're not invoking) interpret that to mean "redirect the output to this file".

  • Process.exec() doesn't work on linux

    I am running an executable on linux machine using
    Runtime rt = Runtime.getRuntime();
    p = rt.exec(comm);
    where cmd is as below:
    local cmd:"/home/spolavar/Lmeasure/LM.exe" "/home/spolavar/Lmeasure/Lmin.txt"
    but i get the following error. why should there be an IOException?
    the path is correct and the executable is very much in that location.
    If i run the command directly on the terminal i get the result without any problem.
    i am not understanding where is the problem?
    however, it use to work fine before.
    java.io.IOException: java.io.IOException: "/home/spolavar/Lmeasure/LM.exe": not found
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:143)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:566)
    at java.lang.Runtime.exec(Runtime.java:428)
    at java.lang.Runtime.exec(Runtime.java:364)
    at java.lang.Runtime.exec(Runtime.java:326)
    at Lmeasure.gui.ExecuteLocalLMImpl.execLM(ExecuteLocalLMImpl.java:264)
    at Lmeasure.gui.ExecuteLocalLMImpl.run(ExecuteLocalLMImpl.java:167)
    at Lmeasure.gui.LMManagerImpl.run(LMManagerImpl.java:36)
    Thanks
    Sri

    FYI this works fine on windows...
    my code is below if anyone is interested:
    import java.lang.Runtime;
    import java.lang.Process;
    import java.io.*;
    public class ExecuteFile{
            public static void main (String []  args){
                    String [] arg1 = {"/usr/bin/mysql -ppassword -e 'source /root/misc_applications/temp.sql'"};
                    cmd(arg1);
            public static void cmd (String [] args){
                    for(int i=0; i<args.length; i++){
                            try{
                                    Runtime rdb = Runtime.getRuntime();
                                    Process pdb = rdb.exec(args);
    System.out.println(args[i]);
    BufferedReader in = new BufferedReader(new InputStreamReader(pdb.getInputStream()));
    String output = null;
    while((output = in.readLine())!= null)
    System.out.println(output);
    BufferedReader errin = new BufferedReader(new InputStreamReader(pdb.getErrorStream()));
    String errtext = null;
    output = null;
    while((output = in.readLine())!= null)
    errtext += output;
    if(errtext != null)
    throw new IOException(errtext);
    }catch(IOException ioe){ioe.printStackTrace();}

  • Runtime.exec ignores the working directory argument

    Hi Folks,
    I need to run a batch file in a particular directory, from a Java program.
    Here, I want to run "startMySQL.bat" from the ./bin directory.
    I used the following code to do so.
         String commandToExecute = "startMySQL.bat";
         File file = new File("bin");
    Process sqlPrcs = Runtime.getRuntime().exec(commandToExecute, null, file);     
    When I run these lines in a program, I get the following exception:
    java.io.IOException: CreateProcess: startMySQL.bat 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 com.aperto.ems.packetmax.AuthenticationScreen.startDB(AuthenticationScreen.java:603)
    at com.aperto.ems.packetmax.AuthenticationScreen.validateUserAndReinitialize(AuthenticationScreen.java:479)
    at com.aperto.ems.packetmax.AuthenticationScreen.access$0(AuthenticationScreen.java:468)
    at com.aperto.ems.packetmax.AuthenticationScreen$OnOKButtonPress.actionPerformed(AuthenticationScreen.java:628)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener$ReleasedAction.actionPerformed(Unknown Source)
    at javax.swing.SwingUtilities.notifyAction(Unknown Source)
    at javax.swing.JComponent.processKeyBinding(Unknown Source)
    at javax.swing.JComponent.processKeyBindings(Unknown Source)
    at javax.swing.JComponent.processKeyEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    "error=2" in Windows mean "not able to find the file".
    Any clues on how I can run the batch file from a particular working directory?
    Thanks!

    Hi,
    I changed the code to print the user.dir output and the absolute path of the file. It looks like this:
    String commandToExecute = "startMySQL.bat";
    File fl = new File("bin");
    System.out.println(fl.getAbsolutePath());
    System.out.println(System.getProperty("user.dir"));
    Process sqlPrcs = Runtime.getRuntime().exec(commandToExecute, null, fl);
    Below is the output I get:
    C:\Program Files\Aperto\WaveCenter\Back-End_Server_2.0_build8\bin
    C:\Program Files\Aperto\WaveCenter\Back-End_Server_2.0_build8
    java.io.IOException: CreateProcess: startMySQL.bat 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 com.aperto.ems.packetmax.AuthenticationScreen.startDB(AuthenticationScreen.java:604)
    at com.aperto.ems.packetmax.AuthenticationScreen.validateUserAndReinitialize(AuthenticationScreen.java:479)
    at com.aperto.ems.packetmax.AuthenticationScreen.access$0(AuthenticationScreen.java:468)
    at com.aperto.ems.packetmax.AuthenticationScreen$OnOKButtonPress.actionPerformed(AuthenticationScreen.java:629)
    I assure you, "startMySQL.bat" is there under "bin"
    Thanks,
    Sandeep

  • Runtime.exec() does not work under Linux

    Hi,
    I have a generic application runner class that runs an external
    program and redirects stdout/stderr to a buffer/file.
    While everythings works just fine under Windows, I get the
    following exception under Linux trying to run the Java interpreter
    'java':
    java.io.IOException: "/usr/lib/SunJava2-1.3.1/jre/bin/java": not found
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:139)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:546)
    at java.lang.Runtime.exec(Runtime.java:413)
    I have checked that the file /usr/lib/SunJava2-1.3.1/jre/bin/java
    exists.
    Any help appreciated!
    Marc

    can I ask how you solved it? I am having a problem
    with quotes just now to and it might help me!I simply tested what the current platform is and
    only used quotes under Windows.
    Marc

  • Runtime.exec does not work for commands with lengthy outputs

    I need to use Runtime.exec to run some custom commands on a Unix box. I have been doing this for quite some time now and had begun to feel comfortable when recently I started facing a problem. The thing is, whenever there is a command which prints a lot of data on to the console, the program is not able to exit from the waitFor method. Is there some thing that can be done about this?
    Following is a part of the code I use:
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec (command);
    System.out.println ("Got the process");
    int exitValue = p.waitFor();
    System.out.println ("Exit value: " + exitValue);When the output of the "command" is lengthy, it hangs after printing "Got the process".
    PS: By lengthy output, I mean that the command results in printing lines to the console which might be more than 100 in number. Say, something like what "ls -R /" would do in Unix / Linux.

    From java.lang.Process API doc:
    The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
    So you need to consume the process' output. Check the StreamGobbler example from this article.
    Hope it helps.

  • Runtim exec() method not working.....giving Exception

    whts the code to use exec() method. i m using it as follows and also catching exception.
    Runtime r=Runtime.getRuntime();
    Process p=r.exec("java A");
    code is giving IOException at runtime with error=2.

    Here is an example I used when I first needed to test the runtime.exec
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TestRuntime {
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("java A");
                InputStream stderr = proc.getErrorStream();
                InputStreamReader isr = new InputStreamReader(stderr);
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                System.out.println("<ERROR>");
                while ( (line = br.readLine()) != null)
                    System.out.println(line);
                System.out.println("</ERROR>");
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }Are you waiting for the process to end before exiting your program?

  • Runtime.exec() does not work normally

    I try to wrapper the oracle connect command on unix using this function:
    runtime.exec("sqlplus username/password@dbinstance")
    it is ok on windows, but on unix, after runing the class, I get nothing. what is the problem?
    Please help me. thanks

    There are several traps with runtime.exec(). The most important one is that you should read
    the output stream of the launched program. Otherwise it will stop running when the console buffer overflows. The size of the buffer differs for various OSes.
    Look at this article:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    It it does not answer your problem, try to search the forums:
    http://search.java.sun.com/Search/java?qt=%2B%22exec%22+-%22Replies%3A+0%22&col=javafrm&rf=0&qp=%2Bforum%3A31
    This problem has been asked hundreds of times.
    Hope, this helps.

  • Runtime.exec() does not work?

    I'm trying to invoke a C++ executable from java using the Runtime.exec() method. The C++ application accepts a filename as a command line argument & opens the file. This C++ app is unicode enabled i.e. it can accept UTF-16 (wide char) parameters. Howevere, when i invoke this application using Java's Runtime.exec() and specify a japanese file name as an argument, the japanese characters get converted to '?' characters by the time they are received in the C++ application. I'm running this application on Windows 2K, default i.e. English version.
    Looking at the source code of Runtime class, it seems that the exec()
    function makes use of a native helper function - execInternal(). Does
    this function support the entire unicode range?
    Is there any way we can avoid the conversion of japanese characters to '?' characters? Also, is there any other alternative for invoking an external application with Unicode (Say, japanese) arguments?
    Please reply ASAP.
    Thanks!

    >
    I'm trying to invoke a C++ executable from java using
    the Runtime.exec() method. The C++ application accepts
    a filename as a command line argument & opens the
    file. This C++ app is unicode enabled i.e. it can
    accept UTF-16 (wide char) parameters. Howevere, when i
    invoke this application using Java's Runtime.exec()
    and specify a japanese file name as an argument, the
    japanese characters get converted to '?' characters by
    the time they are received in the C++ application. I'm
    running this application on Windows 2K, default i.e.
    English version.
    Looking at the source code of Runtime class, it seems
    that the exec()
    function makes use of a native helper function -
    execInternal(). Does
    this function support the entire unicode range?I don't know because I've never tested this case specifically.
    You didn't show your code though. How are you reading in the String? You mentioned that you passed a Japanese character String as a filename argument. I also read that you are running on an English Win2K platform. How did you read that argument in? It may just be that you read the argument in your default encoding(English) and you needed to specify an alternate one.

  • Runtime exec() Problem, change working dir

    Hi!
    I have following problem:
    I want to call an executable from my home-directory under Linux this way:
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("/home/tom/prog/exec-command");
    Unfortunately I'm getting either exception "file not found" (but it's there) or no complain but no program run...
    perhaps something's wrong with the path-name?
    If I call the program in the directory with a shell it works fine.
    Would be very happy if anybody can give a hint!
    Thanks a lot,
    Manuel

    You are interested in the programs output? Does it write to stdout or stderr or both? In any case, my advice is to go multithreading and use one thread to wait for the program to exit, one to read stdout and one to read stderr. If you just use one thread for reading, the program might block. I normally use something like this:
      final int BUFFER = 2048;
      final Process p = Runtime.getRuntime().exec(args);
      //read standard out output of the external executable
      //in seperate thread to avoid I/O deadlocks
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getInputStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.out.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //read standard error output of the external executable
      //in seperate thread for symmetry
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getErrorStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.err.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //Wait for the external process to finish     
      int exitCode = p.waitFor();          
      if ( exitCode != 0 )
        throw new IOException("Executable stopped with error code "+exitCode); Cheers, HJK

  • DI function exec() doesn't work on HPUX

    We created a simple job which contains only a script which invokes a Korn shell script "test.sh". The script should generate an output file. But we tried many different kinds of syntax but couldn't get it work. The syntax we tried are:
    1) exec('/scripts/test.sh', 'out_filename.xml', 0);
    2) exec('ksh', '/scripts/test.sh out_filename.xml', 0);
    3) exec('/bin/ksh', '/scripts/test.sh out_filename.xml', 0);
    DI always generates error messages like "Function <exec> failed to execute program <ksh ksh /scripts/test.sh out_filename.xml> ...". The strange thing is it always print the first parameter twice no matter what you put there. If I don't specify anything for the first parameter, like
    exec('', '/scripts/test.sh out_filename.xml', 0);
    the job would finish immediately but the output file was not generated and we know that the script cannot finish that fast (it takes 30 seconds to generate the output file on the command line).
    I even tried to remove the first line "#!/bin/ksh" from the script but it didn't work either. Can anyone shed some light on this issue? This is DI 11.5.3 on HPUX. Thanks for your help!
    Larry

    exec('/bin/ksh', '-c "/scripts/test.sh out_filename.xml"  ', 0);
    I guess the command
      "ksh test.sh file.xml"
    is not clear if file.xml belongs to the ksh or test.sh. With the -c and the double quotes you make it obvious to the OS.
    I assume you are 100% sure the ksh binary is found in /bin/ folder, not in /usr/bin/ and that your test.sh has the execution permission set for the user the DI jobserver was started from.
    What helped me to resolve exec() function issues is to embed them inside a print() function and use the flag 8 meaning "concat return code & stdout & stderr".
    print(exec('/bin/ksh', '-c "/scripts/test.sh out_filename.xml"  ', 8));

  • Fscommand "exec" doesn't work in Mac (Flash Player 10.1)

    Hi All,
    I am trying to launch an external application using fscommand in Mac ('fscommand' works fine on Windows). I have done following things to make it work:
    Written an apple script to launch a pdf and saved it as "test.app"
    I copied "test.app" to "fscommand" directory. (fscommand is a directory under 'flash projector.app')
    Tried to launch the "test.app" using fscommand, as shown below:
                fscommand("exec", "test.app");   
    But, my efforts went in vain. It did not work. I even tried to copy "fscommand" dir to "Flash Debugger Player.app/Contents/MacOS/", but still I can't make it work.
    More Info:
    Mac version: Mac OS X 10.6.2
    Hardware: Intel Core duo 2
    Flash Player Version: 10.1 (standalone projector)
    Is it something I am missing or is it a bug in Flash Player 10.1? Does anybody could make it work; Please let me know!

    Praveen,
    Im in the same boat. - Im trying to open a mac projector .app from inside another .app by using Fscommand "exec".
    After reading this
    http://www.morgadinho.org/2007/03/12/launching-an-app-with-fscommand-on-mac-os-x/
    have created applescripts with .app extension inside Fscommand folder, but to no avail.
    Have heard anything/ had any resolution yet?
    james

  • Runtime.exec() won't work

    Hi all,
    i've got a program that i want to via a java program,
    in ms-dos, the programma is called by:
    mace2 -n9 -p -m10 -c <puzzle.in> puzzle.outBut in my java program if I use:
    Process mace = Runtime.getRuntime().exec("mace2 -n9 -p -m10 -c <puzzle.in> puzzle.out");the program gets called, but never ends properly, and the java
    program halts.
    Anything wrong? Thanks in advance.

    You can't read, write and run in the same thread - this was tested using the group example and -n4; using -n9 would take a long time.
    import java.io.*;
    class Piper implements Runnable {
      InputStream in;
      OutputStream out;
      Piper (InputStream in, OutputStream out) {
        this.in = new BufferedInputStream(in);
        this.out = new BufferedOutputStream(out);
      public void run () {
        try {
          try {
            try {
              for (int i; (i = in.read()) != -1; ) {
                out.write((byte)i);
            } finally {
              in.close();
            out.flush();
          } finally {
            out.close();
        } catch (IOException ex) {
          ex.printStackTrace();
    public class CallMace {
      static final String pathToMace = "<whatever>\Otter33-Win32\\bin\\";
      static void runMace (String inFile, String outFile) {
        try {
          Process p = Runtime.getRuntime().exec(pathToMace + "mace2 -n9 -p -m10 -c");
          Thread tIn = new Thread(new Piper(new FileInputStream(inFile), p.getOutputStream()));
          Thread tOut = new Thread(new Piper(p.getInputStream(), new FileOutputStream(outFile)));
          tIn.start();                              
          tOut.start();                              
          p.waitFor();
          tIn.join();
          tOut.join();
        } catch (Exception ex) {
          ex.printStackTrace();
      public static void main (String...args) {
        runMace(args[0], args[1]);
    }Pete

  • I'm running Yosemite and get a pop up message when I try to open Adobe Illustrator "To open "Adobe Illustrator CS6" you need to install the legacy Java SE 6 runtime" It doesn't work

    Anyone know how to fix the Adobe Illustrator for Yosemite

    Hi mcollis56,
    You can try to download java from below mentioned link:
    Java for OS X 2014-001
    Thanks,
    Nikhil Gupta

  • Runtime exec problem to execute a C program

    Hi,
    I've spend lot of time trying to find a solution without success...
    My aim is to run a C program from a java application under linux. My C code is the following:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    main(int argc, char **argv){
    printf("hello world \n");
    Once compiled I run my java application wich run the binary through a runtime.exec().
    I followed the example given by
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    with the same input gobblers and threads.
    For some reason it doesn't work: nothing comes out...
    When I call "ls" instead of my binary it works perfectly!
    WHY??
    Any help would be greatly appreciated!

    Thanks for the reply.
    Yes it seems that JNI could be a solution, but it looks a bit complicated an maybe not so well adapted to my purpose.
    The executables I want to execute from my java application don't need any arguments.
    If JNI is really the only way I'll try to use it but is there any good reason why runtime exec doesn't work? It is supposed to execute any executable isn't it?
    cheers

Maybe you are looking for

  • Matlab and ActiveX performanc​e

    I am playing around with using Labview as an ActiveX server with Matlab.  The anticipated application is to run instrument control in Labview and then use ActiveX to transfer data over to Matlab for more processing. The data transfer speed is surpris

  • What went wrong with the control autobackup

    I started a rman autobackup incremental level 1 at 2 am, and I noticed that at the same time, system generated an error in alert log point ing to a trc file in udump: /oracleapp/apps/admin/baanbk/udump/baanbk_ora_491598.trc Oracle Database 10g Enterp

  • How to get the most out of a Macbook Pro?

    I'm about to attend Full Sail University for a baccalaureate in Game Design. They'll be sending me a brand new macbook pro with a bunch of software, and I'll be using it 8+ hours per day. I want to have this laptop last at least the 4 years I'll be i

  • Picking multiple quants from one storage bin

    Hello all, I have a client that purchases copper wire in pallets that are stored initially in storage bins.  During goods issues to production the pallets are split up and, when material is put back in the warehouse,  storage bins end up with multipl

  • When I try to open a particular website I get pageck in the upper left corner and the website won't open

    When I try to open a particular website I get a pageck in the upper left hand corner of the screen and the website won't open.