Runtime.exec( ) exception

Hi All!
Could you please look at this code and give me an idea what could be wrong.
Thanks
String commandStr = "move " + args[0] + " " + args[1];
           System.out.println( commandStr );
           try {
                Process proc = Runtime.getRuntime().exec( commandStr );
                int retValue = proc.exitValue();
                System.out.print ( "Command : " + commandStr );
                System.out.println( "was executed with exit value : " + retValue );
           catch (Throwable t) {
                System.out.println("Caught an exception ");
                t.printStackTrace();
output
move C:/C++ C:/MovedStuff
java.io.IOException: CreateProcess: move C:/C++ C:/MovedStuff error=2
Caught an exception
     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 FileCopier.main(FileCopier.java:92)

There are more things to consider if you are going to run other commands. Mainly, you have to read what the command writes to STDOUT and STDERR otherwise your program will just hang.
I forget where I found my information but I just searched the web for "StreamGobbler" and found www.experts-exchange.com/Developer/ Programming/Q_20428597.html which contains a good code snippet and looks a lot like the code I have.
I've only done this on Windows but it should work on Linux as well. You'll have to have separate code for each operating system, of course, as Java does not know what you are trying to execute it merely passes the command to the shell.
Good luck.
Barry

Similar Messages

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

  • How to capture Runtime.exec() output? doesn't seem to work?

    This is the first time I've used Runtime.exec();
    Here's the code:
    Runtime rt = Runtime.getRuntime();
                process = rt.exec(jobCommand);
                BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line=null;
                while((line=input.readLine()) != null) {
                     System.out.println("OUTPUT: " + line);
                int exitVal = process.waitFor();
            } catch(Exception e) {
                 e.printStackTrace();
            }//end catchas you can see, this is just copied and pasted out of the standard example for this method.
    When it gets to the line:
    while((line=input.readLine()) != null)
    it doesn't read anything. However, when i run the SAME exact command from the windows CMD prompt i get a ton of output.
    what am i doing wrong here?
    thanks.

    Welcome to the forum!
    >
    as you can see, this is just copied and pasted out of the standard example for this method.
    >
    No one can see that - you didn't post a link to the example you said you copied.
    >
    it doesn't read anything. However, when i run the SAME exact command from the windows CMD prompt i get a ton of output.
    >
    No one can see what command you are talking about; you didn't post the commnd or even describe what output you expect to get.
    >
    what am i doing wrong here?
    >
    What you are doing wrong is not providing the code you are using, the command you are using or enough information about what exactly you are doing.
    No one can try to reproduce your problem based on what you posted.

  • 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

  • The Runtime.exec methods doesn't work well on Solaris ???

    I have two threads and I set the different running time.
    I use Runtime.exec to a run the command and use Process to get the process.
    It works properly in the windows2000 platform.
    However, when I transfer the platform to Solaris...and run the program...
    Two threads always at the same time....It is very wired....I always debug
    for 2 days....
    (at first I run "vmstat 1 2" command, later I change to "ls","rmdir"....etc,
    all of them don't work.....
    If I close the Runtime.exec..........Everything works well......)
    And I study the API. I found this message...
    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 Win32, or shell scripts. The created subprocess does
    not have its own terminal or console.
    Could someone share her/his experience.....:(
    And if any other way I can run command inside java code instead of
    Runtime.exec.....???
    Please reply my mail to [email protected] I do appreciate your kindly &
    great help!!!!!!!!
    This is my code.......
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    * <p>ServerThread1</p>
    * <p>??�X???��?�D???�X???, "Vmstat 1 2".</p>
    class ServerThread1 extends Thread{
    private ServerAgent Sa;
    public ServerThread1 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa; file://Assign ServerAgent reference Sa
    public void run(){
    while(true){
    try{
    Thread.sleep(5000);
    catch (Exception e){
    System.out.println("ServerThread1 fails");
    System.out.println("Thread1 is running.");
    try {
    Runtime rt1 = Runtime.getRuntime();
    Process proc1 = rt1.exec("mkdir"); ------>If I close
    rt1.exec , two threads works seperately...........:(
    catch (Exception e) {
    System.out.println("Thread1 Error");
    class ServerThread2 extends Thread{
    private ServerAgent Sa;
    public ServerThread2 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa;
    public void run(){
    while(true){
    try{
    Thread.sleep(15000);
    catch (Exception e){
    System.out.println("ServerThread2 fails");
    System.out.println("Thread2 is running.");
    try {
    Runtime rt2 = Runtime.getRuntime();
    Process proc2 = rt2.exec("vmstat 1 2"); ----->If I don't run
    the rt2.exe, two threads work seperately....
    catch (Exception e) {
    System.out.println("Thread2 Error");
    public class ServerAgent{
    private Vector v1 = new Vector();
    private Vector v2 = new Vector();
    private Hashtable currentData = new Hashtable();
    private static String startUpSwap = null;
    private static String startUpMem = null;
    public static void main(String[] arg) {
    ServerAgent s = new ServerAgent();
    ServerThread1 st1 = new ServerThread1("Thread1",s);
    ServerThread2 st2 = new ServerThread2("Thread2",s);
    st1.start();
    st2.start();

    If I close the Runtime.exec..........Everything works
    well......)You don't empty the output of the command, that blocks the process.
    A citation from
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Why Runtime.exec() hangs
    The JDK's Javadoc documentation provides the answer to this question:
    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.
    Try out something like this:
    String s;
    try {
       Process myProcess =
       Runtime.getRuntime().exec("ls -l"));
       DataInputStream in = new DataInputStream(
              new BufferedInputStream(myProcess.getInputStream()));
        while ((s = in.readLine()) != null) {
            out.println(s);
    catch (IOException e) {
        out.println("Error: " + e);
    }Another source of trouble under Unix is not having the correct permission for that user that executes the Java VM, which will be the permissions for the spawned subprocess. But this probably not the case, as you see something after exit.
    Regards,
    Marc

  • How to give path in Runtime. exec( )

    Hi,
    I am trying to create an user interface, in which, it should open a different file (for example, example.doc)when a button is clicked in the applet. let us say, the path for example.doc is "C:\\WINDOWS\\DeskTOP\\folder1".
    I tried with the following code
    Runtime.getRuntime().exec("C:\\WINDOWS\\Desktop\\folder1\\example.doc");
    but, when I click on the button it is not opening example file and I am getting an exception. I am using Runtime.exec() command for the first time.Anybody can help me with this???

    Since when was a document an executable? The main problem is many people think Runtime.exec () is the same thing as the command line. The answer is, it's not. Typing "example.doc" in the windows terminal emulator (also known as cmd.exe in Windows 2000/XP or command.com in others) will work because example.doc is opened with the application configured to open files with the ".doc" extension.
    However, files ending with ".doc" are not executables. If you wish to open a ".doc" file with the associated application, try this: Runtime.getRuntime ().exec ("cmd /c example.doc"); Not that I don't know if this will work with command.com as I haven't tried, but it should work with cmd.exe without problems.
    Hope it helps.
    Cheers

  • How can I run Runtime.exec command in Java To invoke several other javas?

    Dear Friends:
    I met a problem when I want to use a Java program to run other java processes by Runtime.exec command,
    How can I run Runtime.exec command in Java To invoke several other java processes??
    see code below,
    I want to use HelloHappyCall to call both HappyHoliday.java and HellowWorld.java,
    [1]. main program,
    package abc;
    import java.util.*;
    import java.io.*;
    class HelloHappyCall
         public static void main(String[] args){
              try
                   Runtime.getRuntime().exec("java  -version");
                   Runtime.getRuntime().exec("cmd /c java  HelloWorld "); // here start will create a new process..
                   System.out.println("Never mind abt the bach file execution...");
              catch(Exception ex)
                   System.out.println("Exception occured: " + ex);
    } [2]. sub 1 program
    package abc;
    import java.util.*;
    import java.io.*;
    class HelloWorld
         public static void main(String[] args){
         System.out.println("Hellow World");
    } [3]. Sub 2 program:
    package abc;
    import java.util.*;
    import java.io.*;
    class HappyHoliday
         public static void main(String[] args){
         System.out.println("Happy Holiday!!");
    } When I run, I got following:
    Never mind abt the bach file execution...
    I cannot see both Java version and Hellow World print, what is wrong??
    I use eclipse3.2
    Thanks a lot..

    sunnymanman wrote:
    Thanks,
    But How can I see both programs printout
    "Happy Holiday"
    and
    "Hello World"
    ??First of all, you're not even calling the Happy Holiday one. If you want it to do something, you have to invoke it.
    And by the way, in your comments, you mention that in one case, a new process is created. Actually, new processes are created each time you call Runtime.exec.
    Anyway, if you want the output from the processes, you read it using getInputStream from the Process class. In fact, you really should read that stream anyway (read that URL I sent you to find out why).
    If you want to print that output to the screen, then do so as you'd print anything to the screen.
    in notepad HelloWorld.java, I can see it is opened,
    but in Java, not.I have no idea what you're saying here. It's not relevant whether a source code file is opened in Notepad, when running a program.

  • How to capture output of java files using Runtime.exec

    Hi guys,
    I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
    import java.io.*;
    public class CmdExec {
      public CmdExec() {
      public static void main(String argv[]){
         try {
         String line;
         Runtime rt = Runtime.getRuntime();
         String[] cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
         Process proc = rt.exec(cmd);
         cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
         proc = rt.exec(cmd);
         //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
    public class E {
        public static void main(String[] args) {
            System.out.println("hello world!!!!");
    }Please help :)

    Javapedia: Classpath
    How Classes are Found
    Setting the class path (Windows)
    Setting the class path (Solaris/Linux)
    Understanding the Java ClassLoader
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • How to make Runtime.exec call Linux exec?

    Howdy,
    I am trying to use a combination of 'find' and 'rm' to delete all files with a certain extension in a directory and all of its subdirs.
    Here's the command:
    Process proc = runtime.exec("find " + dir + " -name '*.vcs' -exec rm -rf {} \\;");
    It's failing, not sure why, the exitCode is 1 instead of 0. I'm not sure if it's because I have to escape the '\' character, or if it's because I am calling Linux's 'exec' function within a Java exec() call, or something else entirely.
    The easiest thing to do would be to just use rm, but that doesn't seem to be an option. With rm it seems to be all or nothing -- If I try:
    rm -rf *.vcs
    it fails if it doesn't find a file with that extension in the start directory (even though I've specified -r). But if I enter:
    rm -rf *
    it nukes my directories AND files, something I don't want to happen. I realize this is a Linux thing, I'm just explaining it here as background, just in case.
    Anyway, so is there a way to do this? Perhaps with another system call, without using Linux's exec()?
    Many thanks
    Bob

    import java.io.*;
    public class ExecutingALinuxCommand
        static class PipeInputStreamToOutputStream implements Runnable
            PipeInputStreamToOutputStream(InputStream is, OutputStream os)
                is_ = is;
                os_ = os;
            public void run()
                try
                    byte[] buffer = new byte[1024];
                    for(int count = 0; (count = is_.read(buffer)) >= 0;)
                        os_.write(buffer, 0, count);
                catch (IOException e)
                    e.printStackTrace();
            private final InputStream is_;
            private final OutputStream os_;
        public static void main(String[] args)
            try
                String dir = System.getProperty("user.home") + "/work/dev";
                String[] command = {"sh","-c", "find " + dir + " -name '*.java' -exec grep -l Runtime {} \\;"};
                final Process process = Runtime.getRuntime().exec(command);
                new Thread(new PipeInputStreamToOutputStream(process.getInputStream(), System.out)).start();
                new Thread(new PipeInputStreamToOutputStream(process.getErrorStream(), System.err)).start();
                int returnCode = process.waitFor();
                System.out.println("Return code = " + returnCode);
            catch (Exception e)
                e.printStackTrace();
    }

  • Runtime.exec() fails sometime to execute a command

    Hello,
    I have a program thats using Runtime.exec to execute some external programs sequence with some redirection operators.
    For e.g, I have some command as follows;
    1 - C:\bin\IBRSD.exe IBRSD -s
    2 - C:\bin\mcstat -n @punduk444:5000#mc -l c:\ | grep -i running | grep -v grep |wc -l
    3 - ping punduk444 | grep "100%" | wc -l
    ...etc.
    These command in sequence for a single run. The test program makes multiple such runs. So my problem is sometimes the runtime.exec() fails to execute some of the commands above (typically the 2nd one). The waitFor() returns error code (-1). That is if I loop these commands for say 30 runs then in some 1~4 runs the 2nd command fails to execute and return -1 error code.
    Can some one help me out to as why this is happening? Any help is appreciated
    Thanks,
    ~jaideep
    Herer is the code snippet;
    Runtime runtime = Runtime.getRuntime();
    //create process object to handle result
    Process process = null;
    commandToRun = "cmd /c " + command;
    process = runtime.exec( commandToRun );
    CommandOutputReader cmdError = new CommandOutputReader(process.getErrorStream());
    CommandOutputReader cmdOutput = new CommandOutputReader(process.getInputStream());
    cmdError.start();
    cmdOutput.start();
    CheckProcess chkProcess = new CheckProcess(process);
    chkProcess.start();
    int retValue = process.waitFor();
    if(retValue != 0)
    return -1;
    output = cmdOutput.getOutputData();
    cmdError = null;
    cmdOutput = null;
    chkProcess = null;
    /*******************************supporting CommandOutputReader class *********************************/
    public class CommandOutputReader extends Thread
    private transient InputStream inputStream; //to get output of any command
    private transient String output; //output will store command output
    protected boolean isDone;
    public CommandOutputReader()
    super();
    output = "";
    this.inputStream = null;
    public CommandOutputReader(InputStream stream)
    super();
    output = "";
    this.inputStream = stream;
    public void setStream(InputStream stream)
    this.inputStream = stream;
    public String getOutputData()
    return output;
    public void run()
    if(inputStream != null)
    final BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream), 1024 * 128);
    String line = null;
    try
    while ( (line = bufferReader.readLine()) != null)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.DEBUG,line);
    //output += line + System.getProperty(Constants.ALL_NEWLINE_GETPROPERTY_PARAM);
    output += line + "\r\n";
    System.out.println("<< "+ this.getId() + " >>" + output );
    System.out.println("<< "+ this.getId() + " >>" + "closed the i/p stream...");
    inputStream.close();
    bufferReader.close();
    catch (IOException objIOException)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("io_exeception_reading_cmd_output")+
    objIOException.getMessage());
    output = ResourceString.getString("io_exeception_reading_cmd_output");
    else
    output = "io exeception reading cmd output";
    finally {
    isDone = true;
    public boolean isDone() {
    return isDone;
    /*******************************supporting CommandOutputReader class *********************************/
    /*******************************supporting process controller class *********************************/
    public class CheckProcess extends Thread
    private transient Process monitoredProcess;
    private transient boolean continueLoop ;
    private transient long maxWait = Constants.WAIT_PERIOD;
    public CheckProcess(Process monitoredProcess)
    super();
    this.monitoredProcess = monitoredProcess;
    continueLoop =true;
    public void setMaxWait(final long max)
    this.maxWait = max;
    public void stopProcess()
    continueLoop=false;
    public void run()
    //long start1 = java.util.Calendar.getInstance().getTimeInMillis();
    final long start1 = System.currentTimeMillis();
    while (true && continueLoop)
    // after maxWait millis, stops monitoredProcess and return
    if (System.currentTimeMillis() - start1 > maxWait)
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    return;
    try
    sleep(1000);
    catch (InterruptedException e)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    System.out.println(ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    else
    System.out.println("Exception in sleep" + e.getLocalizedMessage());
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    /*******************************supporting process controller class *********************************/

    Hi,
    Infact the command passed to the exec() is in the form of a batch file, which contains on of these commands. I can not put all commands in one batch file due to inherent nature of the program.
    But my main concern was that, why would it behave like this. If I run the same command for 30 times 1~3 times the same command can not be executed (returns with error code 1, on wiun2k pro) and rest times it works perfectly fine.
    Do you see any abnormality in the code.
    I ahve used the same sequence of code as in the article suggested by
    "masijade". i.e having threads to monitor the process and other threads to read and empty out the input and error streams so that the buffer does not get full.
    But I see here the problem is not of process getting hanged, I sense this because my waitFor() returns with error code as 1, had the process hanged it would not have returned , am I making sense?
    Regards,
    ~jaideep

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

  • 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

  • Problem in Runtime.exec()

    I am trying to launch a new java application from my java program like this-:
    import java.io.*;
    public class test123{
    //String userStr="";
                public static void main(String args[]) throws Exception{
                        Process p = Runtime.getRuntime().exec("java JavaExec",null,currentDir);
                        Thread.sleep(10000);
                        System.out.println("After Destroy");
    } The JavaExec file�s code is -:
    import java.io.*;
    import org.apache.log4j.Logger;
    public class JavaExec
                 static Logger logger = Logger.getLogger("JavaExec.class");
    public static void main(String args[])
    try
                Runtime runtime = Runtime.getRuntime();
                            Process process = runtime.exec("notepad");
                int exitCode=0;
                while(true)
                            //logger.info("Inside the infinite while loop in javaexec");
                            try
                                        exitCode = process.exitValue();
                                        System.out.println(exitCode);
                                        process.destroy();
                                        process = runtime.exec("notepad");
                            catch(IllegalThreadStateException itse)
                                        System.out.println("Inside exception");
    } catch (Throwable t)
    t.printStackTrace();
    }Notepad opens when I execute the test123 class but instead of remaining open even if I close it , I am able to close notepad. The JavaExec only starts processing again when my main quits.
    Please let me know the solution to this problem.....
    Thanks in Advance
    Inder Jeet Singh

    Convoluted at best. You don't need that loop, just useexitCode = process.exitValue();and it will block until notepad exits.
    P.S. Why a Runtime.exec() executing a Java program that does a Runtime.exec() on notepad?

  • Runtime.exec - Too Many Open Files

    System version : Red Hat Enterprise Linux 2.4.21-47.ELsmp AS release 3 (Taroon Update 8)
    JRE version : 1.6.0-b105
    Important : the commands described below are launched from a Web application : Apache Tomcat 6.0.10
    Hello,
    I'm facing a problem already known, but appearantly never really solved ??!! ;)
    When I invoke many system commands with the 'Runtime.exec(...)' method, there are open files that are not released (I can see them with the "lsof" system command) .
    At the end, the unavoidable "too many open files" Exception.
    The lauched commands are "ssh ... " commands.
    In the topics relating to this problem, the solution is always to close all Streams / threads and to explicitely invoke the method "Process.destroy()".
    My problem is that this is what I do ! And I can't do more...
    Here is the code :
           Runtime rt = Runtime.getRuntime();
           Process process = rt.exec("ssh ...");
            // ProcessStreamHolder extends Thread and reads from the InputStream given in constructor...
            ProcessStreamHolder errorStream = new ProcessStreamHolder(process.getErrorStream());
            ProcessStreamHolder outputStream = new ProcessStreamHolder(process.getInputStream());
            errorStream.start();
            outputStream.start();
            exitValue = process.waitFor();
            try {
                errorStream.interrupt();
            } catch (RuntimeException e) {
                logger.warn("...");
            try {
                outputStream.interrupt();
            } catch (RuntimeException e) {
                logger.warn("...");
            try {
                process.getInputStream().close();
            } catch (RuntimeException e) {
                logger.warn("...");
            try {
                process.getOutputStream().close();
            } catch (RuntimeException e) {
                logger.warn("...");
            try {
                process.getErrorStream().close();
            } catch (RuntimeException e) {
                logger.warn("...");
            process.destroy();Does someone know if my code is wrong or if there's a workaround for me ?
    Thanks by advance !
    Richard.

    Don't interrupt those threads. Close the output stream first, then wait for the process to exit, then both threads reading the stdout and stderr of the process should get EOFs, so they should exit naturally, and incidentally close the streams themselves.

  • Spawn a java process using runtime.exec() method

    Hi,
    This is my first post in this forum. I have a small problem. I am trying to spawn a java process using Runtime.getRuntime().exec() method in Solaris. However, there is no result in this check the follwoing program.
    /* Program Starts here */
    import java.io.*;
    public class Test {
    public static void main(String args[]) {
    String cmd[] = {"java", "-version"};
    Runtime runtime = Runtime.getRuntime();
    try{
    Process proc = runtime.exec(cmd);
    }catch(Exception ioException){
    ioException.printStackTrace();
    /* Program ends here */
    There is neither any exception nor any result.
    The result I am expecting is it should print the following:
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
    Please help me out in this regard
    Thanks in advance
    Chotu.

    Yes your right. It is proc.getInputStream() or proc.getErrorStream(). That is what I get for trying to use my memory instead of looking it up. Though hopefully the OP would have seen the return type of the other methods and figured it out.

Maybe you are looking for

  • How to create something like this?

    Hi, i am curious on is this been created? Is it textarea component? but the picture shows that the usernames can be highlighted when mouse Over, also there are small buttons functions like add to Friend List. Any tips? PICTURE

  • Deleting photos from LR3 is excruciatingly slow

    I'm finally getting around to cleaning up a catalog from last year that has several thousand photos that I don't want to keep. I am running into a strange behavior trying to delete these photos from within LR3. If I filter on only photos rated as one

  • Can We Two Different Credit Control Area to 1 company code using cross comp

    Can We Two Different Credit Control Area to 1 company code using cross company code assignment.Tried but giving error at the time of bill release.Experts Can you help?

  • Typekit fonts not loading in Muse

    Hi, I purchased a Creative Cloud Annual Plan and I can't use the Add Web Fonts dialog box within Muse. I run it on a Win XP pro 64bit SP2, Muse working properly if not for that function.. Dialog box appear but  no command is clickable and error is pr

  • Storage Unit Management at WS level and/or Storage Type level??

    Hi all, There are two ways to activate the storage unit management in WM (i.e. Warehouse No, and Storage Type). Does it means if I want only certain storage type to have the function of SU management, I should NOT activate it on the Warehouse number,