Java.lang.Runtime.exec()

When using the exec method I cannot get it to run the specified application when I try to use the Runtime.execString[] cmdArray)
The application I am running is windump, it runs ok when I specify it in the Runtime.exec(String cmd) method.
I need to use the Runtime.exec(String[] cmdArray) option as I need to specify parameters as part of my project. To be exact I need to tell it to output to a text file.
I can do this when running windump from the command prompt, thus cannot understand whty it wont work when I specify the same option from Runtime.exec(..)
Any ideas how to overcome this?
thanks Conor

This works for me on WindowsNT:
try {
     Runtime.getRuntime().exec("cmd.exe /c dir>dirtest.txt");
catch (Exception e) {}
[/code}
Mark

Similar Messages

  • Java.lang.Runtime.exec problem in ubuntu 9.10

    Hi:
    I tried to run some command in the java code , for example "grass64 -text /home/data/location", this command works well in the terminal, however when I call it in the java code I got some excepetions.
    My code is :
    public class Grass {
         public static String grassBatJob="GRASS_BATCH_JOB";
         public void run(String cmd,String jobPath) {
              //set the environments variables
              Map<String, String> env=new HashMap<String, String>();
              env.put(grassBatJob, jobPath);
              String gisDataBase="/home/kk/grass/GrassDataBase";
              String location="spearfish60";
              String mapset="PERMANENT";
              cmd=cmd+" "+gisDataBase+"/"+location+"/"+mapset;
              CommandLine line=new CommandLine(cmd);
              //the real cmd should be >>grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT
              System.out.println("start line=="+line.toString());
              DefaultExecutor de=new DefaultExecutor();
              try {
                   int index=de.execute(line,env);
                   System.out.println(index);
              } catch (ExecuteException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              String jobPath=Grass.class.getResource("grass.sh").getFile();
              new Grass().run("grass64 -text", jobPath);
    The real cmd I want to execute is "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT" with the envrionment variable "GRASS_BATCH_JOB=jobPath",it works well in the ternimal ,however in my application I got the exception"
    java.io.IOException: Cannot run program "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT": java.io.IOException: error=2, No such file or directory
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
         at java.lang.Runtime.exec(Runtime.java:593)
         at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:58)
         at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:246)
         at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:302)
         at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:149)
         at org.kingxip.Grass.run(Grass.java:27)
         at org.kingxip.Grass.main(Grass.java:38)
    Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
         at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
         at java.lang.ProcessImpl.start(ProcessImpl.java:65)
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
         ... 7 more
    I wonder why?

    Thanks for all of your reply, and now I can run the command, however I met some problems when I tried to get the result of the exec.
    The core codes are shown below:
    String cmd="g.version";
    String[] exe={"bash","-c",cmd};
    Process p1=Runtime.getRuntime.exec(exe,env); // the env has been set
    GrassThread outThread=new GrassThread("out", p1.getInputStream());
    outThread.start();
    GrassThread errorThread=new GrassThread("error", p1.getErrorStream());
    errorThread.start();
    int exitVal = p1.waitFor();
    String resu=outThread.sb.toString();
    System.out.println("==========the output start========");
    System.out.println(resu);
    System.out.println("==========the output end========");
    System.out.println("ExitValue: " + exitVal); //------------------> line one
    public class GrassThread extends Thread{
         public StringBuffer sb=new StringBuffer();
         public GrassThread(String type,InputStream is) {
              this.type=type;
              this.is=is;
         public void run() {
              try {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader br = new BufferedReader(isr);
                   String line = null;
                   while ((line = br.readLine()) != null) {
                        System.out.println(type + ">" + line);
                        sb.append(line).append("\r");  // ----------------------------> line two
    }I define a StringBuffer in the GrassThread to save the output (see the code where I marked by "line two"), and when the process complete, I check the StringBuffer to get the output (see code where I marked by "line one"), however the output in the console of the IDE are :
    ----------- output in the console of the IDE start -------------
    ==========the output start========
    ==========the output end========
    ExitValue: 0
    out>GRASS 6.4.0RC5 (2009)
    ----------output in the console of the IDE end--------------------
    I can not understand, in the code "line one", I first get the output using "System.out.println(resu);",then I print the exitvalue,but why the order of the output in the console is not what I expected?
    Another question, the code above assume the output can be got from the Process's getInputStream, however sometimes the output maybe come from the Process's getErrorStream, so how to handle it?
    Edited by: apachemaven on 2010-3-5 ??5:38

  • Java.lang.Runtime.exec() again

    try{
    Process registryProcess = null;
    Runtime r = Runtime.getRuntime();
    String[] cmdArray = {"F:\\windump", ">>new_res.txt"};
    registryProcess = r.exec(cmdArray);
    }catch(Exception ex){
    System.out.println("Exception Caught: " + ex.getMessage());
    ** Have also tried speicfying the command and the parameters all in the one string like so :
    String cmd = "F:\\windump >>F:\\new_res.txt";
    registryProcess = r.exec(cmd);

    try
    String cmd = "cmd /c F:\\windump >> F:\\new_res.txt";
    registryProcess = r.exec(cmd);

  • Invoke exe through java code(using java.lang.Runtime)

    Iam trying to invoke an exe from java code.If i give the complete path for that exe it is running fine .But if i set the environment variable and directly execute the exe through command prompt it iss running fine , but it fails to run when i do the same using java code i.e. java.lang.Runtime.exec function

    Give "//" for directory seperator.
    E.g. r.exec("c://test//test.exe",null);
    Why? That doesn't look correct.It is correct. It will work fine. Try it out.But it doesn't add or solve anything. A forward slash
    does not need to be escaped.'
    It's not even escaping. It's just doubling up. If that works, I'd bet "C://///test///////test.exe" does also.

  • Java.lang.Process.exec()

    I have read a article about the "java.lang.Process.exec()" (url:http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html)
    Having some questions with the example in it.
    The example code:
    import java.util.*;
    import java.io.*;
    public class BadExecJavac
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                //int exitVal = proc.exitValue();
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }The process can run but never complete.
    Why? Just because when invoke the javac.exe without any argument,it will product a set of usage statements that describe how to run the program and the meaning of all the available program options.So the process is in deadlock.
    The question is, when i change the exec("javac") to exec("javac a.java"), in which the "a.java" is not exist, so the jvm should product error:
    error: cannot read: a.java
    1 error
    But after i changed the code and run the class, at this time the process can run and complete.
    The two codes both product some statements,but why the first one never complete,but the second did. Why?

    import java.util.*;
    import java.io.*;
    public class A
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                InputStream is = proc.getErrorStream();
                int i=0;
                while ((i = is.read()) != -1)
                    System.out.print((char)i);
                // int exitVal = proc.exitValue();
                // int exitVal = proc.waitFor();
                // System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }usng this modification, i could see some error messages.
    because exec(cmd) executes the command in a separate process, it will not display the results on the current console. If you want see the results, you should use getInputStream() and getErrorStream().
    good luch ^^

  • Java's Runtime.exec() method

    When you shell out to java's Runtime.exec() method, are the process name and arguments the same for the child process that is spawned.
    We see duplicated processes about the time when our logs tell us this command was run. However, we cannot seem to reproduce this. Has anyone else seen anyone this before?

    That's what I though too. But check this out . . .
    Our code looks as follows:
    private Runtime rt;
    private Process p;
    rt = Rutime.getRuntime();
    p = rt.exec(command);
    This exec() call creates a new process, which is a child of the java process that runs this command. The final process looks like the "command" string that is passed to the exec() method call. In our case, the command is a call to the /usr/bin/mail utility to send out faxes and emails.
    We ran a very tight loop executing the rt.exec() call over and over. What we found was that for a minor fraction of a second, the newly created process looks just like the original process including the same arguments. However, the PID's indicated that one process was the child of the other. This is why it looked like we had 2 of the same processes. WILD!
    Thanks guys!

  • Hi java.lang.System.gc() vs java.lang.Runtime.gc()

    hi all what is the exact diff.,
    java.lang.System.gc() vs java.lang.Runtime.gc()
    why dont I call Runtime.gc() like System.gc(), is ther any possibility ?
    Thanks in advance

    Thanks, but I just want to call Runtime.gc() like
    System.gc() forcefully to invoke finalize() method
    Thanks in advanceThe calls are the same. Read the javadoc:
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#gc()
    public static void gc()
    Runs the garbage collector.
    Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
    The call System.gc() is effectively equivalent to the call:
    Runtime.getRuntime().gc()

  • Invoke RealVNC using java code(java.lang.Runtime)

    I would like to invoke vncviewer exe whenever user presses a button.Please help

    What part are you having trouble with? What have you done so far?
    Note that you have two main problems to solve here.
    Do you know how to perform a given action when a button is pressed? If not, google for a swing tutorial. You'll want some kind of Listener, though I don't know the specific class name.
    Do you know how to invoke another executable program from within a Java app? If not, look into Runtime.exec.

  • Java/lang/Runtime exception

    java.lang.RuntimeException: IOException reading reader invalid byte 1110011 error caused while running sun Wireless tool kit.Can any body please help me to solve this problem. I am using Eclipse 3.3 and also eclipse 3.2
    with sun java wireless toolkit in ubuntu.
    Thanks and Regards,
    Pandian

    Support for the RecipeFox extension is over here: <br />
    http://recipetools.sourceforge.net/phpBB3/index.php

  • Executing a shell script from java using runtime.exec()

    Hi I am trying to create a script (test_script) and execute it -- all within one java program...
    the code compiles and executes perfectly but nothing happens. This is probably because the script does not get changed to the '777' mode although i am trying to do that ... any suggestions ???
    //code
    import java.io.*;
    import java.util.*;
    public class ScriptBuilder
         public ScriptBuilder() {
         public void writeScript() throws java.io.IOException{
         FileWriter writer = new FileWriter(new File("test_script"));
              writer.write("#! /bin/sh\n");
              writer.write("cd prodiags\n");
              writer.write("tar cvf delTask.tar delTask\n");
              writer.write("rm -rf delTask\n");          
              writer.flush();
              writer.close();
    Runtime rt= Runtime.getRuntime();
    String[] cmd = new String[3];
    cmd[0] = "ls";
    cmd[1] = "chmod 777 test_script";
    cmd[2] = "./test_script";
    rt.exec(cmd);
         public static void main (String[] args)throws java.io.IOException
         ScriptBuilder sb = new ScriptBuilder();
         sb.writeScript();
    }

    I don't know exactly but the code written below is working fine try the same with your code .Even with your code instead running the code with
    " ./<filename> ",if you execute it with "sh <filename>" command without changing the mode of the file it is executing properly.
    import java.io.*;
    import java.util.*;
    public class ScriptBuilder
    public ScriptBuilder()
    public void writeScript() throws java.io.IOException
    FileWriter writer = new FileWriter(new File("test_script"));
    writer.write("#! /bin/sh\n");
    writer.write("ll>/home/faiyaz/javaprac/checkll");
    writer.flush();
    writer.close();
    Runtime rt= Runtime.getRuntime();
    rt.exec("chmod 777 test_script");
    rt.exec("./test_script");
    } public static void main (String[] args)throws java.io.IOException
    ScriptBuilder sb = new ScriptBuilder();
    sb.writeScript();
    }

  • Java.lang.Runtime()

    I made a small addition program using 'C'. It accepts 2 no.s and produces the result.
    how can i send the 2 no.s to the C program? Here is the code i tried:
    Runtime r=Runtime.getRuntime();
    Process p=r.exec("add.exe");
    InputStream ios=p.getInputStream();
    OutputStream ops=p.getOutputStream();
    String a="1\n", b="2\n", text;
    ops.write(a.getBytes());
    ops.write(b.getBytes());
    BufferedReader br=new BufferedReader(InputStreamReader(ios));
    while ( (text=br.readLine())!=null)
          System.out.println(text);I'm neither getting any output nor any error. What do i do? Plz help and thanks in advance.

    Maybe this time:
    ops.write(a.getBytes());
    ops.write(b.getBytes());
    ops.flush();
    [/code[                                                                                                                                                                                               

  • I am trying to set up Recipefox to export MasterCook 11. What configurations should be "export" box. I am also getting an error message that Java.lang.Runtime exception. could not create a new folder for the writer.

    When Igo to "Export them" a box shows that my configuration paths are not correct.

    Support for the RecipeFox extension is over here: <br />
    http://recipetools.sourceforge.net/phpBB3/index.php

  • Increasing memory used by java process when calling Runtime.exec()

    Hi everyone!
    I'm running a servlet Oracle iAS 9i, Jserv. It receives an image posted by a user and does a System.exec() which performs a call to convert (an image processing utility included in ImageMagick).
    After a few hours, java process start taking more and more RAM, until it crashes with an error like this:
    Memory: 5394008 free of 134217728 total. (I log this myself)
    Exception: java.io.IOException: Not enough space
    java.lang.UNIXProcess.forkAndExec(), line -2.
    java.lang.UNIXProcess.<init>(), line 54.
    java.lang.Runtime.execInternal(), line -2.
    java.lang.Runtime.exec(), line 553.
    ImageProcessor.convert(), line 235.
    ImageProcessor.createItemPics(), line 124.
    Uploader.doPost(), line 69.
    As you can see, this is not an OutOfMemoryError, but something else in connection with O/S.
    This is not related to hard disk space, since there is a lot of free space in every filesystems
    After restarting the webserver, everything goes back to normal and start increasing RAM again.
    Is there anything I can do? Any help will be gratly appreciated... Thanks!!!
    Dani.-

    Have you had any solutions to this pal?
    I am also suffering. I tried closing the processes by:
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("/opt/sta_rpms.sh " + sFileName);
    proc.waitFor();
    proc.getInputStream().close();
    proc.getOutputStream().close();
    proc.getErrorStream().close();
    proc.destroy();
    proc = null;
    but still after like a day...Though our codes are not alike, it sounds like the same reason.
    Cheers!

  • Error in opening a file with name in chinese characters with Runtime.exec

    The issue at hand is when I try to open a file with file name containing chinese characters in a localized environment in Windows through the following java code:
    Runtime.exec("rundll32 SHELL32.DLL,ShellExec_RunDLL {File_With_FileName_containing_Chinese_character}");
    the following error is thrown by windows.
    Cannot open file "C:\??.txt".
    with the exception
    java.io.IOException: CreateProcess: [Ljava.lang.String;@f5da06 error=2
            at java.lang.Win32Process.create(Native Method)
            at java.lang.Win32Process.<init>(Win32Process.java:66)
            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 Launcher.main(Launcher.java:26)
    When I try to use the same command (shown below) from the Windows Run command, the file opens sucessfully
    rundll32 SHELL32.DLL,ShellExec_RunDLL {File_With_FileName_containing_Chinese_character}
    Please suggest.
    Thanks in advance

    This may be a file association problem.  To solve that:
    In Windows 7:
    1. Right-click the file,
    2. Select "Open With" 
    select [Your Program Here]
    3. Check always use this program. 
    In Windows XP:
    1. Locate the file as you have described above
    2. Right click the file
    3. Select Open with from the pop-up menu
    4. Click Choose default program…
    5. Select Excel in the Recommended Programs box
    6. Check Always use the selected program to open this kind of file
    7. Click on OK.
    1.  Make Excel not available from Office 2007 listed under Programs and Features in Control Panel.
    2. Take a registry backup using the steps given here
    3. In the registry editor window expand HKEY_CLASSES_ROOT and navigate to .xls right and delete it.
    4. Exit Registry Editor
    5. Undo Step 1 to make Excel available.
    6.  Restart the computer and verify it the issue is fixed.
    If this answer solves your problem, please check Mark as Answered. If this answer helps, please click the Vote as Helpful button. Cheers, Shane Devenshire

  • Runtime.exec() works in Win98 but not in XP?

    Hi all!
    I have the following problem: I am using following lines of code in win98 to launch a MSDOS-window from my application (with some arguments to it):
    try {
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("start "+"command.com"+"/k"+"java -cp \""
    +getArgument(directory,false)
    +"\""+" "+getNoExtent(file));
    proc.waitFor();
    catch (Exception ex) {
    ex.printStackTrace();
    This works very well, however in XP it doesnt do a thing (I know that I have to change 'command.com' to 'cmd' or 'cmd.exe'). I have already tried that but it wont work. Instead, this exception occurs while running on XP:
    java.io.IOException: CreateProcess: start cmd 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: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 JSEdit.actionPerformed(JSEdit.java:443)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.AbstractButton.doClick(AbstractButton.java:289)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1
    113)
    at javax.swing.plaf.basic.BasicMenuItemUI$MouseInputHandler.mouseRelease
    d(BasicMenuItemUI.java:943)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    What should I do?
    Thanx!
    Regards
    Veroslav

    Check you string concatenation, you're missing spaces or you are not providing the actual code:
    Process proc = rt.exec("start "+"command.com"+"/k"+"java -cp \""
    +getArgument(directory,false)
    +"\""+" "+getNoExtent(file));Let's dissect:
    String command = "start ";
    // command := "start "
    command += "command.com";
    // command := "start command.com"
    command += "/k"+"java -cp \""
    // command := "start command.com/kjava -cp\""You can always trace these kind of errors by using a debugger. Or dump the string you are passing to System.out. Every comprehensive IDE has a debugger built in, or you can resort to jdb.
    Greets
    Dhek Bhun.

Maybe you are looking for

  • My iPod Nano 6th generation no longer shows up on iTunes

    how do I reconnect my Ipod Nano 6th generation to my iTunes?

  • IPhone 4S 5.0.1 upgrade to 6.1.3 by on air. Is it possible?

    Good day! Exuse me for my fluent English-I am from Russia)) I have Bought a new iphone 4s 64 GB recently. It has 5.0.1 firmware. Today it offered me to update on air to 6.1.3. (it's strange,because ios 7 is actually now) Can I do it or my iphone will

  • Problem with unzipping file

    I am trying to unzip a file using java.util.zip. It is throwing a ZipException in the first line where I instantiate ZipFile object. ZipFile oFile = new ZipFile("/myzip.zip");java.util.jar is not working either. It fails right here: JarFile oFile = n

  • Only get Users that match all Links

    Seemingly a very simple problem, but I can't seem to figure it out. Table below is a table that holds UserId' s and LinkId's. CREATE TABLE UserLink (UserId NUMBER, LinkId NUMBER ); ALTER TABLE UserLink ADD PRIMARY KEY (UserId, LinkId); INSERT INTO Us

  • TDS PRINTING

    Hi Gurus, I am faceing aproblem in TDS printing. I getting this error <b>Business Place for document  could not be determined in T.CODE JINCERT.</b> Pls help me soon Thank U & Regards viks