Calling runtime.exec in menu(swing)

Hi all,
I want to pop up a command (NT) window from a menu in java swing.
1. However I am able to call from the menu, but was Not able to get the batch file (either .bat or .exe) to run in another window
2. and all the output from the batch file did not printout to screen.
any help?
JMenuItem menuItem = null;
startAction = new AbstractAction("Start") {
public void actionPerformed(ActionEvent e) {
displayResult("Starting Application...", e);
Process JobProcess = null;
try {
// JobProcess = Runtime.getRuntime().exec("cmd.exe /c test.bat");
//JobProcess = Runtime.getRuntime().exec("cmd /K start cmd /K test.bat");
//JobProcess = Runtime.getRuntime().exec("cmd.exe /c test.bat"); //works
JobProcess = Runtime.getRuntime().exec("test.bat"); // works
JobProcess.waitFor();
int i = JobProcess.exitValue();
catch (Exception ex) {
textArea.append(ex.getMessage());
in the test.bat :
echo "this is test" > test.txt
thanks
andrew

I don't believe you can ues redirection (>) when executing a command. Your program must handle the output itself. Add code something like:
String line;
BufferedReader output = new BufferedReader( new InputStreamReader( JobProcess.getInputStream() ) );
while ( (line = output.readLine()) != null )
          System.out.println( line );
output.close();Note: the variable JobProcess should be renamed to jobProcess. The Java convention is to use uppercase for class names.

Similar Messages

  • Tidal abends with error message: Jvm call Runtime.exec() returned null

    just wandering if this error "Jvm call Runtime.exec() returned null  Command[chmod 777] launch failed." is a tidal error and not a job command error returned from the OS server.
    thanks,
    warren

    I'm having the same problem...
    Have you been able to solve your problem yet?

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

  • Using GUI Runtime.exec() another GUI, later come up, previous gone

    I try to run
    try {
         Runtime rt = Runtime.getRuntime();
         Process process = rt.exec("1.bat");
    InputStream stdin = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<OUTPUT>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
         int exitVal = process.exitValue();
         System.out.println("Process exitValue: " + exitVal);                         
    catch (Throwable e) {
         e.printStackTrace();
    1.bat file have
    ================
    del *.class
    set path=%path%;c:\j2sdk1.4.2\bin
    javac IDE.java
    java IDE
    I run the Runtime.exec code in Swing GUI, I will compile another
    Swing GUI (IDE.java) and run it. It work, but after when IDE GUI popup,
    all the button in the first calling GUI is gone, anyone have solution for it ? Thanks in advance.

    Your code is probably being executed in the event thread of the first application, thus blocking any and all screen updates.
    You should wrap the code in a separate Thread and start it in parallell.

  • How do you prevent MS-DOS window from appearing during Runtime.exec()?

    The question below was attached to the answer for Question of the Week No. 21. I'm having the same problem. Does anyone know the answer? Put another way does anyone know how javaw does it?
    Fri Dec 18 09:59:52 PST 1998
    rkarasek
    On Windows NT 4.0, how can I prevent CreateProcess()
    from creating a cmd.exe window when using javaw and
    Runtime.exec()? No such cmd.exe window is created if
    instead I run "java" from the command line.
    I have a C++ server named "foo", and have created
    a Java applcation with Swing GUI named "foo.java".
    This GUI captures configuration information and
    then uses Runtime.exec() to start the C++ app, with
    a socket established between the Java app and C++
    app for later communication.
    This is all working fine, and the Java application
    and GUI working as expected. When I run "java foo"
    from either the NT command shell (cmd.exe) or MKS
    Korn shell (sh.exe) the Java application/GUI starts,
    and when it calls Runtime.exec() my C++ process is
    started as what appears to be a child process of the
    "java" process, that is, no cmd.exe window is created
    during the Runtime.exec("foo.exe") call.
    However, when running the same Java application from
    a shortcut on the desktop via "javaw", when I invoke
    Runtime.exec() a cmd.exe window is created before my
    C++ server is started. While things are running
    ok and my Java app can still communicate with my
    C++ server, is there anyway I can prevent this
    cmd.exe window from being created, and instead, have
    my C++ server run as a child process of javaw (or
    an independent process without a cmd.exe)?

    cmd always opens a dos window - use another console interpreter instead or just call the programm directly.
    i.e.
    Runetime.exec("c:\\myprogram.exe");
    OR
    The following demonstrates executing a command without bringing up a popup. import java.io.*;
    public class Test {
      public static void main (String args[]) throws IOException {
        String[] command = {
          "C:\\winnt\\system32\\cmd.exe", "/y", "/c",
          "dir"};
        Process p = Runtime.getRuntime().exec(command);
        InputStream is = p.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
          System.out.println(line);
    }However....
    According to bug number 4244515 in Sun's Bug Parade (http://developer.java.sun.com/developer/bugParade/bugs/4244515.html), javaw doesn't always work without bringing up new window.

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

  • Start a new java process using Runtime.Exec() seems to ignore the -Xmx

    I am working with a process that requires a minimum of 1.5 GB to run and works better if more is available.
    So I am determining how much memory is available at startup and restarting the jre by calling
    Runtime.exec("java -Dcom.sun.management.jmxremote=true -Xmx1500M -jar XXX.jar")
    which reinvokes the same process with a new max memory size.
    The initial call to the process is
    java -Dcom.sun.management.jmxremote=true -Xmx3500M -jar XXX.jar
    The initial call returns 3262251008 from Runtime.maxmemory()
    When reinvoked through Runtime.exec() as above
    Runtime.maxmemory() still returns 3262251008
    Is there a way to separate the new process from the size specified by the parent process?

    That is strange. Here is a program I wrote which calls itself recursively.
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    import java.util.ArrayList;
    import static java.util.Arrays.asList;
    public class MemorySize {
        public static void main(String... args) throws IOException, InterruptedException {
            System.out.println("Maximum memory size= "+Runtime.getRuntime().maxMemory());
            if (args.length == 0) return;
            List<String> cmd = new ArrayList<String>();
            cmd.add("java");
            cmd.add("-cp");
            cmd.add(System.getProperty("java.class.path"));
            cmd.add("-Xmx"+args[0]+'m');
            cmd.add("MemorySize");
            cmd.addAll(asList(args).subList(1,args.length));
            Process p = new ProcessBuilder(cmd).start();
            readin(p.getErrorStream());
            readin(p.getInputStream());
        private static void readin(final InputStream in) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        byte[] bytes = new byte[1024];
                        int len;
                        while((len = in.read(bytes))>0)
                            System.out.write(bytes, 0, len);
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
            }).start();
    }If you run this with the args 128 96 33 222 it prints out
    Maximum memory size= 66650112
    Maximum memory size= 133234688
    Maximum memory size= 99942400
    Maximum memory size= 35389440
    Maximum memory size= 231014400

  • Running interactive command with Runtime.exec

    I'm trying to run a command via the Runtime.exec interface.
    Occasionally, the command needs to prompt for additional information. The response depends on the specific configuration, however, the command returns a list of options and then waits for a response.
    However, when the command waits for the response, my Java app hangs.
    After I call Runtime.exec, I create 2 threads to consume the contents of stderr and stdout. I then start them and call proc.waitFor()
    I would expect to see the output of the command in the stdout stream even though the command hasn't exited. I had hoped to parse the output to determine the necessary response. However, the calls to read the contents of the stdout and stderr streams block and I never see any output.
    How can I get access to the contents of those streams while the command is still running? Is this supported through the Runtime.exec interface?
    Thanks,
    Shawn

    This article should help:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Runtime.exec() on a server

    Hi there,
    I am just wondering if it is possible to have a servlet call runtime.exec() on the server side computer to start up a new process. Thanks.

    Yes it can.

  • Runtime.exec hang

    I used Runtime class to run a 3rd party exe. If I just called
    Runtime.exec("3rd.exe whatever"), 3rd.exe would run half way
    then hang. If I called Runtime.exec("start 3rd.exe whatever"),
    3rd.exe would run successfully. However, Runtime.getInputStream
    couldn't receive the output from 3rd.exe.
    Is any way I can get the output from 3rd.exe with "start 3rd.exe
    whatever"?

    Hi,KellanMom :
    I also experienced this problem.
    You should read sth from Process's inputStream,
    outputStream and errorStream.
    You can browse "http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html" to get details.
    Regards.
    Sunway

  • Difference between command line and Runtime.exec()

    Hi all.
    I'm coding some lines to call sqlldr program.
    System info:
    OS: Win2k server
    Java platform: JSK 1.4
    DBMS: Oracle 9i
    I've tested sqlldr in command line and it is OK. But when i call Runtime.exec("sqlldr user/pass@servicename control=mycontrol.ctl")
    the ErrorStream show that: Message 2100 not found,No message file for product=RDBMS ,facility=UL...
    So i had to put a String array which contained "ORACLE_HOME" as the second parameter of exec method. But there's another error appear:
    SQL*Loader-704: Internal error: ulconnect: OCIServerAttach [0]
    ORA-12560: TNS:protocol adapter error
    I checked tnsnames.ora and it's OK. I do the command line again and it's still OK. Why did Runtime.exec("...") method get Error.
    Does Someone solve it for me.
    Thanks so much.

    I'm having the similar/same issue.
    I'm trying to run SQLLdr from JAVA.
    From a command line, it works fine.. From within JAVA, I get..
    SQL*Loader-704: Internal error: ulconnect: OCIServerAttach [0]
    ORA-12640: Authentication adapter initialization failed.
    Did you find a solution to your problem?

  • Runtime.exec with a unix shell script

    I've done a lot of google'ing and haven't found a definitive answer to my question, including the JavaWorld article that is pointed to quite often. Scenario1 - The program calling Runtime.exec is running in /dir1 and I have a script called test.sh in /dir2 (neither directory are in the path). If I call Runtime.exec("test.sh", null, "/dir2"), I get java.io.IOException: test.sh: not found. However, if I do "touch test.sh" AND "chmod +x test.sh" in /dir1 and call the same exec, it works AND runs the script in /dir2 not /dir1?!?! Also, if I copy /dir2/test.sh /dir1/test.sh and I call exec("test.sh"), it works fine. Scenario2 - If I get rid of /dir1/test.sh and call exec("/dir2/test.sh", null, "/dir2") OR exec("/bin/sh test.sh", null, "/dir2") - both of those work. I just don't get Scenario1. Why does having the dummy executable test.sh in /dir1 allow it to run in /dir2 OR if the script is in the local directory of the process calling exec, why does it work without adding the path? It doesn't seem consistent. Seems like the working directory I specify isn't set before trying to run it or something. On the flip side, if I have a java class in /dir2 called test.class, I can call exec("java test", null, "/dir2") and it just runs without jumping through any hoops - although I think the explanation for that is that "java" is in the path. Let me know what you think.
    Gary

    I think the problem is that the three argument version of exec specifies the command to run (should be full path to it if it is not in the current dir), the environment, then the working directory. The working directory will not help java to find the command to run in the first place. The following does work as you say:
    Runtime.exec("/bin/sh test.sh",null,"/dir2");This is because the full path to the command (/bin/sh) is specified, that runs in directory /dir2 then tries to find test.sh which it finds there.
    Basically to run anything, you should specify the full path in the command, the working directory will not help java find it.
    Dave

  • Runtime.exec() and fork() and Process

    So let me see if I understand this correctly, and if I don't please fill me in. If I call the following piece of codeRuntime.getRuntime().exec("chgrp rcsweb " + path+fs+orgName);
    Runtime.getRuntime().exec("chmod 660 " + path+fs+orgName);where path is the real path to a file, fs is short for File.spearator and orgName is the name of a file, then in the Unix environment, it will fork off a process.
    First, I seem to remember one forum topic that mentioned not forgetting about killing the process returned by exec, so I guess I need to add that to my code.
    Second, since I am forking off this process inside of a J2EE container, am I actually forming off the entire container, or just the Servlet where Runtime is called, or what?
    Third, how can I prevent the error java.io.IOException: Not enough space
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:54)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:546)
    at java.lang.Runtime.exec(Runtime.java:413)
    at java.lang.Runtime.exec(Runtime.java:356)
    at java.lang.Runtime.exec(Runtime.java:320)when I do not have the option of changing my VM size? Is killing the Process (and using waitFor()) going to take care of this issue?
    I appreciate your help.

    OK, after writing a few test programs, it is indeed clear..on unix (at least on solaris) when calling runtime.exec(..) The ENTIRE VM does indeed get forked. Therefore if your current Memory allocation for you VM is sitting at say 64MB (or you initial memory setting), another 64MB process will be created, even if you doing something as a simple
    exec("ls");
    I also tried putting runtime.exec call in its own thread hoping that if it was not in the main thread, that only that process would be forked..to no avail..the entire vm is indeed forked everytime...making runtime.exec damn near useless for server side work, and very dangerious..as you can essentialy assume you always need 2x your memory requirements.
    If anyone has figured out a workaround...any suggestions greatly appreciated.
    Some thoughts on some work-arounds
    1. Run 2 VMs (then when native calls are required..send a message to the 'native-calling vm' (insure its memory footprint is very low)
    2. Write your exec method via JNI (or does JNI calls also result in a fork of the vm on unix..)
    Test code below (threaded version)
    import java.util.*;
    import java.io.*;
    public class test5 extends Thread
         public void run()
              int loops = 0;
              while (true)
                   loops++;
                   System.out.println("---- iteration " loops "---");
                   makeNativeCall();
         public static void main(String[] args)
              try
                   System.out.println("testing on OS: " + System.getProperty("os.name"));
                   // Allocate a nice chunk of memory
                   byte[] bytes = new byte[1024 * 1000 * 50];
                   test5 tst = new test5();
                   tst.start();
                   while (true)
                        Thread.sleep(1000);
         catch(Exception e)
         {e.printStackTrace();}
    public void makeNativeCall()
              Runtime runtime = Runtime.getRuntime();
    InputStream stderr = null;
    InputStream stdout = null;
              OutputStream stdin = null;
    Process proc = null;
    long totalMem = (long)(runtime.totalMemory()/1024);
    long freeMem = (long)(runtime.freeMemory()/1024);
    long usedMem = (long)((totalMem - freeMem));
    System.out.println("VM REPORT: TOTAL(" totalMem") FREE("+freeMem+") USED(" usedMem")" );
    try
    proc = runtime.exec("sleep 1");
    stderr = proc.getInputStream();
    stdout = proc.getErrorStream();
    stdin = proc.getOutputStream();
    String line = null;
    int i = 0;
    String error = "";
    int exitVal = proc.waitFor();
    if (exitVal != 0)
    System.out.println("ERROR " +exitVal);
    System.out.println("DETIAL" +error);
    catch(Exception e)
    e.printStackTrace();
    finally
    if (stderr != null)
    try{stderr.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdout != null)
    try{stdout.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdin != null)
    try{stdin.close();}catch(Exception ignore){ignore.printStackTrace();}
    if (proc != null)
    try{proc.destroy();}catch(Exception ignore){ignore.printStackTrace();}

  • Runtime.exec() with envp[] array

    I ran into an unsual problem.
    If I set an env array variable to something (at least one pair), then certain applications fail to start through Runtime.exec(command[], env[]). For example, my own java classes that require various xml and ftp libraries. The particular exception has been mentioned on the forum ( ie. Unrecognized Windows Sockets error: 10106:).
    It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
    So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
    thanks,
    eugene

    >
    It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
    So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
    >
    If you're using 1.5, you can create a java.lang.ProcessBuilder object rather than calling Runtime.exec(). The ProcessBuilder inherits the environment of the calling process, but then allows you to update individual entries.
    In 1.4, I don't believe that you can get a complete copy of the invoker's environment.

  • Runtime.exec using extended envp

    Hello,
    I would like to call Runtime.exec(String[], String[]), using the already existing environment variables with some modifications. Anyone have a tip how to accomplish this?

    ugly hack, yes but it should work:
    in pseudocode:
    Process p = Runtime.exec(my Shell's name);
    p.getOutputStream().write("setenv stuff"); // do this to modify your enviornment
    p.getOutputStream().write("my executable");
    That would allow you to modify the enviornment of your child process.

Maybe you are looking for