Runtime.exec() and batch files

I am having a problem on Windows 2000 while trying to execute a batch file with the Runtime.exec() method. Basically, the exit value returned from the call to Runtime.exec(), returned specifically by the waitFor() method in the Process class, is always zero, even if the batch file fails miserably. After looking into batch files further, it seems to me that the only way to get the exit value of the commands run in the batch file back to the Runtime.exec() call is to put "EXIT %ERRORLEVEL%" in the batch file. What this actually does is exit the command(cmd) shell that the batch file was running in with the exit code of the last command run. This is all great when calling the batch file with a Runtime.exec() call, but when you run it in a cmd window, the window closes when the batch file completes, because the call to EXIT exits the entire shell. I guess i'm just wondering, am i correct in assuming the exit value returned to the java process is going to be the exit value of the shell in which the batch file is running? I need to have the exit value actually indicate whether the batch file ran successfully or not, and if i have to put in the EXIT %ERRORLEVE% (which exits the cmd shell with the exit value of the last command run), then i'll do that, but if someone knows a better way of doing this, i am all ears. Thanks in advance

To run any command from java code, the method is
Runtime.getRuntime().exec( myCommandString )
Where, myCommandString is something like "/full/pathname/command".
If the pathname contains spaces (specifically in Windows), e.g. "c:\program files\windows\notepad", then enclose it in quotes within the quoted string. Or pre-tokenize them into elements of an array and call exec(String[] cmd) instead of exec(String cmd).
From JDK1.3 there are two new overloaded Runtime.exec() methods. These allow you to specify starting directory for the child process.
Note, there is a gotcha associated with reading output from commands. When the runtime exec's the process, it passes to it 3 streams, for stdin, stdout, and stderr; the out and err are buffered but the buffer size isn't very big. When your process runs, it reads (if needed) from in, and writes to out and err.
If it doesn't write more than the buffer-size, it can run to completion.
But if it tries to write more data to one or the other stream than the buffer can hold, the write blocks, and your process hangs, waiting for you to empty the buffer so it can write some more.
So after the exec call, get the streams, and read from them in a loop until they both hit end-of-stream (don't block on either one, just read whatever is available from each, each loop iteration).
Then when the streams have ended, call the process.waitFor() method to let it finish dying.
Now, here is a code snippet how you achieve this.
String strCommand = "cmd.exe /c " + strCommand;
// For Solaris / unix it will be
// String strCommand = "/usr/cobra/sol/runInstaller.sh";
boolean bWait = true;
//execute the command
try
     Runtime r = Runtime.getRuntime();
     Process pr = r.exec(strCommand);
     Process pr = r.exec(callAndArgs);
     BufferedInputStream bis =new BufferedInputStream(pr.getInputStream ());
     int c=0;
     /** Outlet for IO for the process **/
     while (c!=-1)
          c=bis.read();
     /**Now wait for the process to get finished **/
     if(bWait == true)
          pr.waitFor();
          pr.destroy();
catch(Exception e)
     System.out.println("Could not execute process " + strCommand);
     return(false);

Similar Messages

  • Please help how to run System commands and batch files thru java program

    Sir,
    I want execute OS commands like dir,cls..etc and batch files,.exe filesthru java program.
    I have tried it sofar thru Runtime.getRuntime().exec("execute.bat");
    but it is not working.anybody knows about how to run the system commands thru java please give me the code.
    thank you,
    regards,
    j.mouli

    I've seen other posts with this questions, and answers. Unfortunately I didn't pay much attention. But the basic idea is to exec command.com and pass the specifc batch or command as an argument.

  • Reading InputStream from Runtime.exec() and ffmpeg?

    I've got a lot of things going on here and I'm having trouble debugging. I'm working on a streaming music player, and the platform only handles MP3 natively. Specifically, the method that handles incoming requests has to return an InputStream for further processing upstream (out of my visibility).
    I'm trying to extend the music player to play AAC files with the extension ".m4a". To do this, my plan is to transcode from MP3 to AAC using Runtime.exec() and ffmpeg, and then return an InputStream that contains the MP3. This works fine if I use ffmpeg to transcode to a temp file, and then return a FileInputStream constructed from that temp file. But like I said, this is supposed to be a steaming music player, and the blocking for the ~30 seconds it takes to completely transcode to a file is too much of a delay.
    So what I'm trying to do is have ffmpeg transcode to stdout, and then use Process.getInputStream() to return the InputStream that contains ffmpeg's stdout while the transcoding is still going on. This doesn't work and I'm not sure why. (I'm fairly new to java, and this is the first time I've used Runtime.) My player just hangs there. I know Runtime is picky about exhausting the stdout and stderr streams, so I'm not sure if it's something related to that, or if I somehow need to buffer the stdout before returning it, or if I need to run something in a different thread, or if I'm just completely barking up the wrong tree.
    If anyone has any experience with something like this, or can point me at some code that implements something similar, I'd appreciate the help.
    Below a sample of the code in question. Also, for what it's worth, all of the console messages that I put in there are printing, but the music doesn't play.
       public InputStream getStream(String uri) throws IOException
                 System.out.println("Entering Factory.getStream()");
                  System.out.flush();
                File file = new File(URLDecoder.decode(uri, "UTF-8"));
                if (file.exists())
                     if(file.getPath().toLowerCase().endsWith(".mp3")) {
                            // This code for playing MP3 files works correctly
                          System.out.println("Playing MP3");
                          System.out.flush();
                          InputStream in = new FileInputStream(file);
                          return in;
                     else if(file.getPath().toLowerCase().endsWith(".m4a")){
                          System.out.println("Playing M4A");
                          System.out.flush();
                          // Create array for ffmpeg command line
                            // This command line transcodes to STDOUT
                          String[] command = { this.ffmpeg_path,
                                                             "-i", 
                                                             "input.m4a",
                                                             "-acodec",
                                                             "libmp3lame",
                                                             "-ac",
                                                             "2",
                                                             "-ab",
                                                             "256",
                                                             "-f",
                                                             "mp3",
                          // Begin transcoding with ffmpeg
                          System.out.println("Transcoding...");
                          System.out.flush();
                          Runtime runtime = Runtime.getRuntime();
                          Process ffmpeg = runtime.exec(command);
                          // Must exhaust error stream, or the application can become deadlocked.
                          System.out.println("Exhausting stderr...");
                          System.out.flush();
                          this.exhaustInputStream(ffmpeg.getErrorStream());
                          // Return ffmpeg's stdout as an input stream
                          System.out.println("Returning stdout...");
                          System.out.flush();
                          return ffmpeg.getInputStream();
                     else {
                          System.out.println("Unsupported Audio File");
                          System.out.flush();
                          return null;
                else
                    // We aren't requesting a file, so let the API handle the request upstream...
                    return super.getStream(uri);
         private void exhaustInputStream(final InputStream inputStream) {
                  // Since InputStream.read() blocks, exhast the stream in a separate thread
                  new Thread() {
                       public void run() {
                            try {
                                 while(inputStream.read() >= 0) {
                                      // Just throw the bytes away
                            catch(IOException e) {
                                 e.printStackTrace();
                  }.start();
             }

    Read this article
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Runtime.exec and setting environment variables

    Runtime.exec and setting environment variables
    I need a decent example which works on Windows.
    Got any?

    Thank you.
    I was hoping for an example of the use of
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runti
    e.html#exec(java.lang.String,%20java.lang.String[]) or
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runti
    e.html#exec(java.lang.String,%20java.lang.String[],%20j
    va.io.File) which take environment variable
    information such as PATH.
    The reason is because there is a library which is
    being loaded via loadLibrary (
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Syste
    .html#loadLibrary(java.lang.String) ). However, for
    the child process to find the library the PATH needs
    to be updated.
    Any example regarding changing the PATH variable via
    Java so that libraries can be loaded and processes
    created? (Perhaps, I should make a new post and
    restate the question with this more explicit
    information?)
    That won't work. LoadLibrary occurs in the JVM environment. As I said you can't change the JVM environment via exec().
    If the shared library needs something in the path then you are going to have to set the path before your application starts up.
    If you just need to load the library from someplace that is not on the path then you should be using System.load().

  • ALE-Interface and batch file

    Hi,
    So far we have transferred Data from one system to main system through ALE-Interface and Batch file. Now we are thinking to harmonize and optimize this process and run all data transfers though ALE-Interface and eliminate Batch File process.
    Can anybody tell me, why the ALE-Interface is better than Batch file for data transfers?
    Thanks

    Batch file is carried out at offline and at certain time intervals
    where as ALE is online transfer and while triggering a particular tcode it can be made to trigger
    This is why ALE is best
    cheers
    S.Janagar

  • EXEC and EXE files

    I have found some exec and exe files in with my photos in my finder.  I beleive these are old windows filesthat wre transferred over when I switched to Mac and would like to delete them but don't want to cause any issues if these files are usable and needed on my MacBook Pro.  Thanks for your help.

    You are welcome.
    Allan

  • Runtime.exec and exitValue

    hi all,
    i know about the miolion of topics about this object, but i've a question a little bit more specific.
    I have a part of my code that needs to launch external command . I want to save the output of these commands, but i have to minimize the number of thread spawned. In addtion, i cannot know the number of command launched, so the thread number will became an important factor to bound.
    At the same time i need to write something at the end of the output file, so i need to know when the process launched has terminated.
    What i did:
    //  main
    //  here create a thread for process control
    //   procControlThread
    public void launchCommand(String cmd, String file, long ID){
      Process p  = Runtime.exec(cmd+" 1 >> "+file);
       procControlThread.addObj(p,file).
    // in the procControlThread
    public void addObj(Process p, String file){
         synchronized(struct){
              storeSomeWhere(p,file);
    public void run(){
       Iterator i;
      while(boolean){
         synchronized(struct){
            i=struct.iterator();
             while(i.hasNext()){
                MyObj o = (MyObj)i.next();
                 int exitCode;
                  try{
                    exitCode=o.getProcess().exitValue()
                   }catch(IllegalThreadStateException e){
                          // process has not yet finished
                         continue;
                    // process has finished
                    // print in the file where is logged
                   //  the stdout fo the command
                    printSomething(o.getFile(),exitCode);
                     remove(o);
           Thread.sleep(10*1000);    
    // where printSomething
    // create  a Printwriter using a FileOutputStream.well, sometimes i get FileNotFoundException in the printSomething where is mentioned that the file is currently owned by another process.
    do I miss something in the exit code?
    I should using Process.WaitFor()? [ in this case I have to create one thread for controlling one process!]
    -- jdk 1.3.1
    Really thanks in advance.
    T.

    Seems like it should work. Obviously the code you posted is not the same as what you're running though (as it can't compile e.g. while (boolean)), so I'd wonder about what you're really doing.

  • Runtime Exec and ProcessBuilder

    I have an object (textTicket) which is a formatted transaction label. Here is an example:
    CROSS PLAINS QUARRY CROSS PLAINS TN 37049 2549
    MATL SPREADING NOT GUARANTEED
    615-654-9942 TOLL FREE 877-654-9942
    Date: 01/19/2009 04:45:46
    Job No: PU-2008
    Q Num::
    Cust No: 30000001 Src Num::
    Sold To: CASH SALE
    Address: INTERNAL
    NASHVILLE,TN 37202
    Ord By:
    Ord No: Rate Zone:
    Location:THANKS YOU
    Mat. & Haul170.28 Sev Tax:0 Tax16.60
    Acc Total:1308.16
    Total186.88
    3/4 TO 4/67'S
    Gross: 40500 St. Item:
    Tare: 12120 P.O.: MIKE MILLER
    Net: 28380.0
    Net Tons: 14.19
    Proj:
    Truck #: 1
    Hauler: Phy Truck: 248251
    I am attempting to pass this textTicket object to a shell script that will send it out the port for printing. I have tried using the Java Comm API however, we have intermittent problems with the API running on an Oracle Appserver. Sometimes, the data never gets sent to the port. So what I am trying to do is just call a shell script that echos the textTicket out the port via redirection. The problem arise when I use the ProcessBuilder or runtime exec and I have to convert the textTicket to a string via textTicket.toString. The textTicket then losing all of its formatting. Any ideas on how to keep the formatting as I am passing the textTicket to the shell script.

    My example did not save into the post very well. For instance, the first line "Cross Plains Quarry" should be center on the paper. The object contains \t\t to get it center.
    For example on the runtime.exec, I am doing the following
    public void printShell(String port, String string){
         String[] params={"/usr/ts/bin/prttick.sh", string, port};
         try {
                   Process p=Runtime.getRuntime().exec(params);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   SerialCommunicator.logger.debug("error" + e.getMessage());
    The variable string is textTicket.toString();

  • MySQLDump and Batch Files

    Hello all,
    I've been using the mysql connector package to populate and retrieve data from a mysql database. Two questions. First, I have recently become very fond of the mysqldump feature attached with the mysql package. Is there a way to call somthing like that from my connector module? ... or any other mysql "-esque" commands for that matter? (ie show tables, show create table someTable) ...
    I know that the first command I issue is actually a "USE myDatabaseName" to point the connector module at the correct databse. If the USE command is a mysql command, then I'm lead to believe that commands like SHOW will also be legit. However, what would the return structure be? ... would that also be some kind of ResultSet?
    Anyway the other question would be about the execution of batch files like the ones a mysqldump command would generate. I know that I am able to open the dumped text file and populate and run the commands via the methods:
    addBatch(String sql)throws SQLException // to populate
    executeBatch() // to run.. but is there a method that already does that?
    Thanks in advance
    -Curt

    Hi,
    Try Runtime.getRuntime().exec("batchfile.bat");
    Check out Class Runtime for more info.
    -adam

  • Runtime.exec() and white space

    Hello,
    I am attempting to run a DOS -based hydrological modeling from NT using the Runtime.exec() method. When executing the command:
    "Hec1.exe filename"
    the model runs successfully.
    When I try executing the command:
    "Hec1.exe filename > null", the method recognizes the string array as "Hec1.exe filename>null", which causes the model to fail.
    Here is the code that I use to execute the process:
    Runtime rt = Runtime.getRuntime();
    String[] cmd = new String[4];
    cmd[0] = "Hec1.exe";
    cmd[1] = inputFile;
    cmd[2] = ">";
    cmd[3] = "null";
    Process p = rt.exec(cmd);
    Hopefully, there is some sort of workaround that one of you knows.
    Thanks for your time.
    -Joel Finkel

    and yes that batch file is correct but if you want it to be more usefull change that filename to $1 or %1 i forget which(been working in both *NIX and DOS too long)                                                                                                                                                                                                                                                                                                                                       

  • Runtime.exec and locked window

    So I'm working in a Swing application guaranteed to run only on Windows systems using Java 1.6 u 7. The users want a help button to launch a local web browser and point to the company's web site.
    After reading online and finding that getDesktop.browse() sometimes crashes in that version of Java, I use Runtime.exec("rundll ...") to kick off the local browser with the appropriate web address.
    The browser comes up appropriately, but the original Swing application's mouse pointer converts to an hourglass; I can click on the original window and get results but I can't open a new window.
    So I create a short thread implementing the Runnable interface and put the Runtime.exec call in that thread; I assume the problem is that the process is interfering with the GUI thread, and putting the Runtime.exec call in a separate thread will clear the problem up. It doesn't work; I still have the hourglass.
    I read online that some processes require that their input and error streams be consumed, or they may block; That shouldn't be a problem with internet explorer, but I add two threads to consume those streams; still no change.
    I also tried getDesktop().browse() anyway, and in a separate thread, and had the same problem.
    Does anyone have any suggestions?
    Respectfully,
    Brian P.

    Okay.
    First, let's look at the basic client.
    As you can see, when asked to show a window,
    it puts it in a separate thread for rendering:
    public class Client     
    // Show one example method
         private void showNewWindow(Window window)
              ourLogger.info("New request to display window: " + window.getClass().getName());
              if (window instanceof ClientWindow)
                   try
                        ((ClientWindow) window).bindFrames();
                        ((ClientWindow) window).setClient(this);
                        if (window instanceof ClientJDialog)
                             window = new ClientJDialog((ClientJDialog) window);
                        else
                             correctSize(window);
                        showCenter(window);
                        synchronized(myWindows)
                             myWindows.add(window);
                        counter = 0;
                        thread.hide();
                   catch (Exception re)
                        ourLogger.error("Client error while trying to show window", re);
                        ((ClientWindow) window).unbindFrames(false);
              else
                   throw new Error(window.getClass().getName() + " is NOT an instance of ClientWindow");
    // Snip some more
    At this same level on this class, I had originally put a showHelp() procedure with a single
    command thus:
         public void showHelp()
              Desktop.getDesktop().browse(java.net.URI.create(<help web site>));
    Simple, eh? But that gave me the hourglass as discussed. So I pushed it into a new thread.
    It eventually mutated thus:
         public void showHelp()
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
              //windows only
              Runtime rt = Runtime.getRuntime();
              Process p = rt.exec("rundll32 url.dll,FileProtocolHandler " + "<help URL>");
              StreamGobbler s1 = new StreamGobbler ("stdin", p.getInputStream ());
              StreamGobbler s2 = new StreamGobbler ("stderr", p.getErrorStream ());
              s1.start ();
              s2.start ();
              try {
              p.waitFor();
              } catch (java.lang.InterruptedException e) {}
    So as you can see, I ditched Desktop from Runtime and added a pair of stream consumers
    to ensure I wasn't having the stream problem our second poster discussed. Still no joy.
    I eventually replaced the url call with an attempt to invoke a simple batch file which
    did nothing, and I still had the same problem. I still have an hour glass, even when
    the process has been pushed into a new thread as you can see.
    Respectfully,
    Brian P.
    Edited by: pendell on Apr 16, 2010 3:14 PM

  • Runtime.exec() and subprocesses

    I am running a bat file through Runtime.exec(). Conetent of bat file look
    likes following
    E:\Progra~1\Brio\SQRServer\ORA\BINW\sqrw d:/brio/par/par_pqa.sqr
    ibprod/active1@pscore -oC:/TEMP/sqr.log -printer:pd 88
    d:/Brio_Reports/report1.pdf d:/brio/
    exit
    Now this batch file starts another executable program. That program creates
    a report in a particular directory and exit the process. When I run this
    file from command prompt it runs fine. But if I try same thing from
    Runtime.exec(), my program hangs.
    From windows process monitor tools it seems that it start a new process but
    that process never ends. If I end that process forcefully then pointer
    again returns to my java program.
    any idea how to solve this problem.

    Is there maybe any stdout or stderr (console so to say) output which is not taken care of when the thing is called from Java?

  • UNIX Problem with method Runtime exec(String[],String[],File)

    Hello !!
    i'm french
    scuse my english
    I got a probleme with method exec(String[],String[],File) of Runtime Class
    i don't have any probleme when my program runs on Windows NT but the same program on UNIX doesnt execute my command..
    When i use exec(String[]) methode i dont have this problem ...but i need the second one methode because i have to execute my command in a different directory than the JAVA program.
    I need that results of this command are placed in this drectory so that i can't use an exex() like that :
    exemple with a perl :
    "perl /toto/titi/hello.pl"
    I want to execute this :
    "perl hello.pl" (and hello.pl is placed in /toto/titi)
    Conclusion :
    the exec(String[],String[],File) solution is ok with NT ...
    but with UNIX ????
    Is there other solution ??
    Should i do a "cd" command before my execution ? how can i do this ??
    Thanks !!!!

    Could you post your source code (only relevant part)
    Raghu

  • Runtime.exec() with .bat-files in a jar

    Hi All,
    I've written a java-Program, which calls .bat-files per Runtime.exec() for some OS-specific tasks.
    Everything works fine, but if I want to pack the whole code and the .bat-files into several jars, I can't get the bat-files to run. I have tried to get it to work with "getClass().getResource()" as I do the same for my Images, and the returned URL seems to be OK so far (something like jar:file:/c:/test.jar! testpkg/test.bat). I converted this URL into a String and tried to run Runtime.exec() with it, but I always get a Runtime-Exception.
    The String looks exactly like the URL, when I print them to console.
    These bat-files are essential for the application and I would not try to pack them into a jar if I hadn't to distribute this application as a signed applet to unknown users, too.
    I hope there is anyone out there who can tell me if and how it is possible to run an external program out of java, which is packed into a jar, so thanx in advance to any helpful replies.
    acdeka

    You can't run the .bats simply because the shell can't access it. You tell it to run a file that simply doesn't exist in the OS.

  • Fscommand and Batch Files

    Hello, been wrestling with this one for a bit. I am trying to
    figure out what code to use that would let me push a button ( on
    release ) in my standalone projector , and have a batch file
    execute.. is this possible ?

    yes it is posible
    create your .bat file,
    put in the "fscommand" folder relative to your projector file
    for your button
    on(release){
    fscommand("exec", "filename.bat");
    }

Maybe you are looking for

  • How do I transfer PDF files from iPad to MacBook Pro

    hi there, ccan someone please help with this as I want to upgrade my iPad and want to store on PDF files onto my MacBook Pro so I can then download them onto my new iPad. thanks

  • Oracle 8.1.5 EE- interMedia 8.1.5 Compilations Errors

    Greetings, Im runnin` Oracle 8.1.5 EE, with interMedia 8.1.5 in a windowsNT|2000 Environment and my PATH and CLASSPATH are correctly setup... Running Jakarta Tomcat as the JSP/Servlet Engine as well as JDK 1.2 ======= Do I need anything else ?? =====

  • HT1725 Download of a song was corrupted, what do I do

    I have been purchasing some music from the iTunes store today using iTunes on my Windows 7 PC.  Two of the songs have not downloaded.  An error message appeared to say that the file was corrupted, when I check the list of songs purchased I see next t

  • Mac mini audio output

    Hi, i've seen this interesting program http://www.algoriddim.net/index.html for djs. These djs program usually use to way to work: - dual sound card - mutiple output on a single sound card This program use the second approach.... but mac mini has onl

  • How do we retrieve the category instances matching a search expression?

    Consider the following (simplified) example: We archive consolidated reports. Reports come from different branches each containing the data for multiple departments. We create a category containing attributes for the branch, department, and report da