Runtime.exec(command)

hi experts,
I am trying to execute a set of commands from java program
eg: from command prompt
java CommandExecutor c:\winnt\notepad.exe c:\some.exe c:\onemorecommand.exe
and inside the CommandExecutor main method..
public static void main(String []arg)
for(i = 0; i < arg.length; i++)
Runtime.getRuntime().exec(arg(i));
the above code is executing all the command one after the other, but I want to execute the above commands squentially, i.e I want to execute the second command only after finishing the first command and the third after finishing the second and so on depending upon the arguments passed, how can I acheive this...
I have tried to use the Process which is returned by the exec(arg) method but the exitValue() returns same value before execution and after execution.
thanks,
krishna

This is the code I use for this very purpose and it works great. Here you go:
* Wrapper for Runtime.exec
* No console output is generated for the command executed.
* Use <code>process.getOutputStream()</code> to write data out that will be used as
* input to the process. Don't forget to include <code>\n</code> <code>\r</code>
* characters the process is expecting.
* Use <code>process.getInputStream</code> to get the data the process squirts out to
* stdout.
* It is recommended to wrap this call into a seperate thread as to not lock up the
* main AWT event processing thread. (generally seperate threads are needed for both
* the STDOUT and STDIN to avoid deadlock)
* @param theCommand fully qualified #.exe or *.com command for windows etc.
* @see   exec, shell, command, cmd, forDOS, forNT
public static Process exec( String theCommand, boolean wait )
     Process process;
     try
          process = Runtime.getRuntime().exec( theCommand );
     catch ( IOException theException )
          return null;
     if ( wait )
          try
               process.waitFor();
          catch ( InterruptedException theInterruptedException )
     return process;
}

Similar Messages

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

  • Feedback from runtime.exec(command)

    Hi,
    I hope someone can point out the problem with the following. I have a method that is supposed to execute a shell command. The shell command would look something like the following:
    serctl add 351 password [email protected]
    However when this command is executed in a shell/command line a prompt is shown ("MySql password:")asking for a password. Once the user enters the password, the user is added. My code currently executes the first half of the command but gets stuck on the password prompt. My code stops by the line "before the loop" and never enters the inner loop. So obviously my code isn't working properly to say that if the response is a password prompt, to pass it the password variable.
    Any ideas?
    Many Thanks.
    void addUser(String username, String password, String email, String passwd, HttpServletResponse response) throws IOException {
       String[] command = {"serctl", "add", username, password, email};
       //String[] command = {"pstree"};
       Runtime runtime = Runtime.getRuntime();
       Process process = null;
       response.setContentType(CONTENT_TYPE);
       PrintWriter out = response.getWriter();
       String s = "something";
       try {
         process = runtime.exec(command);
         System.out.println("Process is: " + process);
         System.out.println("Command is: " + command);
         BufferedReader in =
         new BufferedReader(new InputStreamReader(process.getInputStream()));
         BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
         OutputStream stdout = process.getOutputStream();
         System.out.println("before the loop");
         s=in.readLine();
         System.out.println(s);
         System.out.println(s);
         System.out.println(in);
         System.out.println(stdout);
         //while((s=in.readLine())!= null)
         while((s=in.readLine()).equals("MySql password: "))
           //s = in.readLine();
           System.out.println(in.readLine());
           System.out.println(s);
           out.println(s);
           if (s.equals("MySql password:  ")) {
             System.out.println("Must be equal to MySql password;");
             //stdout.write(passwd.getBytes());
             //stdout.write(adminpassword);
             //stdout.flush();
             //break;
        System.out.println("after the loop");
         System.out.println("Here is the standard error of the command(if any):\n");
         while ((s = error.readLine()) != null){
           System.out.println(s);
         stdout.close();
         in.close();
         error.close();
         out.println(in);
         out.println("<html>");
         out.println("<body bgcolor=\"#FFFCCC\">");
         out.println("You have successfully added a new user.<br><br>");
         out.println("User " + username + " has been created ");
         out.println("</body></html>");
        catch (Exception e) {
              System.out.println("Uh oh! Error adding new user.");
              e.printStackTrace();
    }

    Just a random observation:
    Sometimes programs that prompt for passwords do it in a way that is impossible to redirect (or at least requires special trickery, such as creating a pseudo-TTY). E.g. in Unix this involves opening /dev/tty and using that instead of stdout & stdin. This is done to make sure there really is a person who knows the password sitting there in front of the teletype.
    I don't know if the "serctl" program does that. If stdout&stdin redirection does not appear to work then it is a possibility.
    A quick googling for "serctl" reveals:
    Commands labeled with (*) will prompt for a MySQL password.
    If the variable PW is set, the password will not be prompted.
    which might or might not be an easier way to deal with this particular program. If it indeed is the same "serctl" program.

  • Running jar in unix using runtime exec command

    Hi, i want to run a jar in unix with the runtime.exec() command,
    but i couldn't manage to do it
    Here is the code
    dene = new String[] {"command","pwd","java tr.com.meteksan.pdocs.pdf.html2pdf "+ f.getAbsolutePath() + " " + pdfPath};
              System.out.println("Creating PDF");
              FileOutputStream fos = new FileOutputStream(new File(pdfPath));
              Runtime rt = Runtime.getRuntime();
              for(int i = 0 ; i < dene.length ; i++)
                  System.out.println("komut = "+dene);
              Process proc = rt.exec(dene);
              // any error message?
              StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // any output?
              StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", fos); // kick them off
              errorGobbler.start();
              outputGobbler.start();
              // any error???
              int exitVal = proc.waitFor();
              System.out.println("ExitValue: " + exitVal);
              fos.flush();
              fos.close();
    when i run this program, the exit value of the process is 0
    can you tell me whats wrong?

    i changed the string to be executed to:
                             dene = new String[] {"sh","-c","java -classpath \"" + Sabit.PDF_TOOL_PATH
                                  + "avalon-framework-4.2.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "batik-all-1.6.jar:" + Sabit.PDF_TOOL_PATH
                                  + "commons-io-1.1.jar:" + Sabit.PDF_TOOL_PATH
                                  + "commons-logging-1.0.4.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "fop.jar:" + Sabit.PDF_TOOL_PATH + "serializer-2.7.0.jar:"
                                  + Sabit.PDF_TOOL_PATH + "Tidy.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xalan-2.7.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "xercesImpl-2.7.1.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xml-apis-1.3.02.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xmlgraphics-commons-1.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "html2pdf.jar:\" tr.com.meteksan.pdocs.pdf.html2pdf "
                                  + f.getAbsolutePath() + " " + pdfPath};     
    and it works now ;)
    thanks...

  • How to display Runtime.exec() command line output via swing

    Hi all, I'm new to java but have a pretty good understanding of it. I'm just not familiar with all the different classes. I'm having trouble capturing the output from a command I'm running from my program. I'm using Runtime.exec(cmdarray) and I'm trying to display the output/results to a JFrame. Once I get the output to display in a JFrame, I'd like it to be almost like a java command prompt where I can type into it incase the command requires user interaction.
    The command executes fine, but I just don't know how to get the results of the command when executed. The command is executed when I click a JButton, which I'd like to then open a JFrame, Popup window or something to display the command results while allowing user interaction.
    Any examples would be appreciated.
    Thank you for your help in advance and I apologize if I'm not clear.

    You can get the standard output of the program with Process.getInputStream. (It's output from the process, but input to your program.)
    This assumes of course that the program you're running is a console program that reads/writes to standard input/output.
    In fact, you really should read from standard output and standard error from the process you start, even if you're not planning to use them. Read this:
    When Runtime Exec Won't

  • Runtime.exec command with spaces

    I'm having problems using exec on (unix) commands that take filenames as a parameter - eg chmod.
    The problem is that I've been blessed with some filenames which contain spaces and I can't figure out a way to pass these through.
    The code I'm trying is :
    String fs="/";
    String droot="home";
    String fname="tom test";
    String fullFileName=fs + droot + fs + fname;
    String outlist[] = runCommand("chmod 777 " + fullFileName );
    if fname contains no spaces, then this will work fine, but (as in the example above) if it contains a space, then I get an error (can't find files).
    Any ideas?
    Thanks
    Tom

    The reason that putting quotes around the filename works on the command line is that they affect how the command line interprets them.
    However, Runtime.exec does not intepret the quotes as special characters. If you have a space in an argument, you should use the Runtime.exec method that takes a String[] argument, and place each argument in an array element.

  • Runtime exec command parameters with SSH

    hey,
    Im trying to run a unix command using Process proc = Runtime.getRuntime().exec(command);
    It works fine until I tried to combine it with multiple commands.
    For example, I'm trying to run:
    ssh [email protected] 'ls -al'
    This returns a exit value of -1, command not found.
    ssh [email protected] ls works fine so I suspect its related to the extra parameters.
    I checked the Javadoc page for exec:
    The command argument is parsed into tokens and then executed as a command in a separate process. The token parsing is done by a StringTokenizer created by the call:
    new StringTokenizer(command)
    As expected, it tokenized:
    ssh
    [email protected]
    'ls
    -al'
    Is there any way to bypass this default tokenization by exec to include quotes as one token?
    If anyone has any ideas, let me know! Thanks!

    thanks, solves that part.. but if i use execute command with ssh and bsub(a clustering job queue-submitter), it does ot return the correct value.
    For example, if i do ssh [email protected] bsub -I ls using exec and the waitFor() method, the waitFor waits indefinitely.
    I can tell it ran the job and ended, because i checked via bjobs and it finished. So why isn't the java app getting the exit code from waitFor() back?
    If I run the program on the targeted machine, bsub -I ls, it works correctly.
    If i type in the console, ssh [email protected] bsub -I ls, it returns back the results correctly.
    info regarding bsub and bjobs here http://www.ncsa.uiuc.edu/UserInfo/Resources/Hardware/XeonCluster/Doc/Jobs.html

  • Runtime.exec() command to open default pdf reader

    Hello
    I want to launch a pdf-file (from within the code) on the system default pdf-reader. Can I somehow retrieve the path to the default pdf-reader and use it like this:
    String pdfReaderPath = retrievePDFreaderpath(); // ????
    String filename = new String("E:\\Test.pdf");
    String[ ] open = {pdfReaderPath , filename};
    try {
    Process proc = Runtime.getRuntime().exec(filename);
    } catch (IOException e) {
    e.printStackTrace();
    Thank you!

    I am new to java programming. I am trying to launch a pdf file from a share drive, but I am getting the following error.
    C:\Misc Java>java PdfExec
    java.io.IOException: CreateProcess: I:/Bass/FRMGEB01.2005 0204 Invoice.pdf erro
    =193
    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 PdfExec.main(PdfExec.java:24)
    Following is my simple code.
    import java.io.*;
    public class PdfExec {
    public static void main(String argv[]) {
    try {
    Process proc = Runtime.getRuntime().exec("//whmax/WHMAX-COMMON/Bass/FRMGEB01.2005 0204 Invoice.pdf");
    catch (IOException e) {
    e.printStackTrace();
    Any help will be appreciated. Thx!

  • Problem in executing RunTime.exec() commands

    Hello EveryBody
    I have a problem.i have to zip the photos that r uploaded by the users and sumit it to the lab person.for that i zip these photos and give the lab person to download that zip.
    But the problem is that when ever i zip 30 to 40 photos its work fantastic.but more the 50 photos not get zip.I have used the code as follow.
    // Here tr=ru
    //dest=distinaction path of the file
    // src=source path of the file
    try
         Runtime rt = Runtime.getRuntime();
         String [] cmd={"zip",tr,dest,src};
    Process p2=rt.exec(cmd,null,dir2);//
         p2.waitFor();
    }catch(Exception e2){
    out.println("HOTO EXCEPTION "+e2.toString());
    Since no zip file is created for big size photo and also it not shows any error.can anybody help me it is urgent.
    Thanks a lot
    R

    zip reports the files as it progresses. It this report is too long, zip's outpbut buffer gets filled and if you do not read it from your Java program, zip will block.

  • Launch Command Line Scanner with Runtime.exec()

    Hi im trying to develop all the process of a common Antivirus ,
    I have a command line anti-virus. But when i try to scan a single file mi code doesnt work.
    I made the following code:
    Runtime runtime = Runtime.getRuntime();
    commands = new String[] {"cmd.exe", "/c","C:\\KAVCLineScanner\\kavecscan.exe","C:\\anfed\\a.txt"};
    Process p =runtime.exec(commands);
    BufferedReader b =new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    String line=null;
    while( (line=b.readLine())!=null){
    System.out.println(line);
    I think the problem is my parameter where i send the file to scan "C:\\anfed\\a.txt", because if i execute this instruction from MSDOS, the process doesnt have problems.
    I also made a .bat file with the instructions but i have the same problem :(
    Thanks for any advise

    I think java naming is from programmer's point of view, so the output stream of the process would be the inputstream to the programmer, hence I am trying to write to my outputstream, which is actually the process' inputstream.

  • 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

  • Using Runtime.exec on a Unix System

    hi,
    I have a web service which executes a command line process 'Runtime.exec(command)'. When the server starts to go on a high load I start to get "IOException: Not Enough Space" which I understand means that I am running out of swap space. No problem as I can increase the swap space to cope with demand. The problem is that I have read that when JVM attempts a fork on a Unix system it temporarily creates a new JVM with the same space requirements as the app server JVM. So if I set my app server to require 1GB memory, I am likely to need to set up swap so that it has 1GB * Number of Parallel Processes. I need to know if this is correct. Our application today does not limit the number of Runtime.exec commands which can be run in parallel and if the above is true we are going to have a problem ensuring we don't run out of memory.
    Can any one verify this or suggest other solutions to the problem?
    Thanks
    Stephen

    hi,
    Yes, very helpful jwenting! Problem is that we are working with legacy systems where we have few other options. If you can give any positive input it's not worth leaving your option at all.
    Thanks
    Stephen

  • Executing a runtime.exec statement from an ejb

    Hi all,
    relativly new to j2ee. I need to use the runtime.exec command to uncompress a set of files from an ejb.
    So far, ive tried that and even the most basic commands like
    /usr/bin/ll *
    and i don't get any response back other than: exit value = 2
    when executing:
    Runtime runtime = Runtime.getRuntime();
    // Process proc = runtime.exec("/usr/bin/uncompress "+this.localFileStore+"*.Z");
    Process proc = runtime.exec("/usr/bin/ll * ");
    // put a BufferedReader on the ls output
    InputStream inputstream = proc.getInputStream();
    InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
    BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
    // read the ls output
    String line;
    while ((line = bufferedreader.readLine()) != null) {
    System.out.println(line);
    // check for ls failure
    try {
    if (proc.waitFor() != 0) {
    System.err.println("exit value = " + proc.exitValue());
    catch (InterruptedException e) {
    System.err.println(e);
    No output from the buffered reader. Any one have any ideas as to why i cannot execute any runtime commands? This is also related to the thread i created where i'm looking for a java library for uncompressing a unix compressed file (unix compress = *.z and not zip or gz files). I think my only two options are to either use the runtime to uncompress these files or.. use some java library to uncompress these files. Let me know if anyone can offer any hints/helpfull comments/libs
    Thanks a bunch

    I might be wrong on this one, but I believe using Runtime.exec() would generally be frowned upon when invoked from an EJB. The reason? EJB implies a remote call. Can you guarantee that a given native process or service will be available on all possible remote nodes that the EJB might be deployed on? Maybe. Can it actually be achieved? Yes. Is it in the spirit of EJB? Probably not.
    - Saish

  • Opening a new browser using Runtime.exec()...

    I am trying to open a new IE browser window (from Windows) using Runtime.exec( ) command. The problem is that it uses the existing browser window instead of opening a new window. (opens a new window only if there isn't any other browser window)
    Here is the snippet of code that I am using to do this:
    String WIN_PATH = "rundll32";
    String WIN_FLAG = "url.dll,FileProtocolHandler";
    String url = "http://www.cnn.com";
    String cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
    Process p = Runtime.getRuntime().exec(cmd);
    Thanks in advance.
    -Kishore

    >
    opening browser window seems to be easy task, >Even easier with [Desktop.browse(URI)|http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#browse(java.net.URI)].
    >
    ..can someone help me with closing browser window from java?>Which browser window?
    If you're app. opens a page that you control, it can be done from the web page. See [Have a Java button close the browser window|http://www.rgagnon.com/javadetails/java-0282.html] or the JS based [Close the browser|http://www.rgagnon.com/jsdetails/js-0079.html].
    If you do not control the page, don't close it - the user knows where the little 'x' button is.
    As an aside, despite being opposite ends of the one question, I do not consider this question to be 'part' of the current thread. I think you would have been better off starting a dedicated thread and explaining more fully what the use case is (and adding lots of Dukes).

  • How do I copy a file to a remote server using runtime exec - plz Help!

    Hi,
    I am trying to copy a file to a remote server using a runtime exec command as follows:
    Runtime.getRuntime().exec("scp "+getProperty(ListNewHandsetDetailsConstant.PROP_OUTPUT_PATH_JAR)+getProperty(ListNewHandsetDetailsConstant.PROP_OUTPUT_JAR_NAME)+".jar "+" "+getProperty(ListNewHandsetDetailsConstant.PROP_OUTPUT_PATH_TWO_USERNAME)+"@"+getProperty(ListNewHandsetDetailsConstant.PROP_OUTPUT_PATH_TWO_URL)+":"+getProperty(ListNewHandsetDetailsConstant.PROP_OUTPUT_PATH_TWO_JAR));
    Problem is this statement does not execute, as when I try it directly on command line, it requests for a password. Any suggestions on how I can get rid of that? I think I might have to configure my ssh_config file, but when I did some "Googling", I found the configuration settings of a ssh2_config file. I tried those (changing it to Host-based Authentication), but it didn't recognise them. Please help, this is so urgent!
    Regards,
    Simz

    Don't use Runtime.exec (or ProcessBuilder) for this. Check out JSch at JCraft (or some other Java SSH API.

Maybe you are looking for

  • How to add a symbol to the beginning of a project?

    I have a pretty intricate Animate composition.  I want to add a simple Symbol/Animation at the beginning.  I've tried inserting time and it did nothing.  Basically, I just want to shift everything over a couple of frames.  I thought of turning the ba

  • An external drive for my MacBook 13-inch Aluminium (Late 2008)

    My 250GB x 2.4GHz MacBook with 2GB RAM now only has 87 GB available. I'm sure that the main reason for this is the 15,000 + images I have saved in iPhoto. Of course, it's pretty slow to do anything at all these days, too, so I'm thinking I'll take ad

  • CDRW/DVDROM combo drive unable to write

    I tried searching the forum, but nothing seemed to fit.  I've just installed cdw and graveman, and neither of them are letting me write my cd.  Graveman detects the drive in the devices menu, but won't let me select it to write to (the only option it

  • Question mark help please (? in Finder window Toolbar)

    Hi there Since my upgrade to Snow Leopard, I have the following question mark in open windows (see pic below): Anyone know what it is, or how to make it vanish? Thanks, Francis

  • How to find out back end mapping program for Idoc ?

    HI Experts, Iam new to ALE IIDOCS .. i have a issue in existing idoc . Some data maping problem is there in the existing idocs I need to find out back end program for this perticular idoc  no . Exactly where they have written the maping code  . How t