How do I execute an external .exe?

easy question I hope.
I'm just making a front-end program with some buttons on it. You push a button, and when you do, an external EXE is called.

Here is something that should help. Runtime.exec() is actually quite complicated even though it's interface is seemingly not (hinting that it's a bad API design):
You should be able to fill in any missing external references w/o difficulty.
package com.solutions400;
import java.util.*;
import java.io.*;
import java.util.logging.*;
* Wraps the complexities of Runtime.exec().
* @author  Joshua Allen
* @created December 10, 2002
public class RuntimeExec
     private static final Logger myLog = SystemDetails.log();
     private Process myProc;
     private StreamGobbler myErrorStream, myOutStream;
     // Access is synchronized so that the check and interrupt call can be an
     // atomic action.  Hence the reason for not using Boolean.FALSE.
     private MutableBoolean myIsWaiting = new MutableBoolean(false);
      * Number of milliseconds to wait for a process to finish before
      * interrupting it when getting the output and/or exit value.
     public final static int TIMEOUT = 1000 * 60;
      * Value returned by exitValue() if the process did not terminate before the
      * timeout and hence true exitValue is unknown.
     public final static int EXIT_VALUE_INTERRUPTED = -999;
     public RuntimeExec(String command)
     throws IOException
          Runtime os = Runtime.getRuntime();
          myProc = os.exec(command);
          myErrorStream = new StreamGobbler(myProc.getErrorStream());
          myOutStream = new StreamGobbler(myProc.getInputStream());
          myErrorStream.start();
          myOutStream.start();
      * @return stderr ouput from command.  Will only wait at most a minute for
      *     the
     public String getError() {
          try {
               myErrorStream.join(TIMEOUT);
          } catch (InterruptedException e) {
               myLog.log(Level.FINE, "Joining interrupted.", e);
          return myErrorStream.getOut();
      * @return stdout output from command. 
     public String getOut() {
          try {
               myOutStream.join(TIMEOUT);
          } catch (InterruptedException e) {
               myLog.log(Level.FINE, "Joining interrupted.", e);
          return myOutStream.getOut();
      * @return exit value of command.  EXIT_VALUE_INTERRUPTED if the process
      *     was interrupted before it terminated.
     public int exitValue() {
          final Thread thisThread = Thread.currentThread();
          Thread t = new Thread() {
               public void run() {
                    Helpers.sleep(TIMEOUT);
                    synchronized (myIsWaiting) {
                         if (myIsWaiting.get()) {
                              thisThread.interrupt();
          t.start();
          synchronized (myIsWaiting) {
               myIsWaiting.set(true);
          waitFor();
          synchronized (myIsWaiting) {
               myIsWaiting.set(false);
          try {
               return myProc.exitValue();
          } catch (IllegalThreadStateException e) {
               myLog.log(Level.FINE, "Process did not exit.", e);
               if (myLog.isLoggable(Level.FINER)) {
                    myLog.exiting(Runtime.class.getName(), "exitValue",
                              new Integer(EXIT_VALUE_INTERRUPTED));
               return EXIT_VALUE_INTERRUPTED;
      * Waits for the process to finish.
     public void waitFor() {
          try {
               myProc.waitFor();
          } catch (InterruptedException e) {
               myLog.log(Level.FINE, "Waiting interrupted.", e);
     private class StreamGobbler
     extends Thread
          Reader myIn;
          CharArrayWriter myBufOut = new CharArrayWriter();
          StreamGobbler(InputStream in)
               myIn = new BufferedReader(new InputStreamReader(in));
          public String getOut() {
               return new String(myBufOut.toCharArray());
          public void run()
               Writer out = null;
               try     {
                    out = new BufferedWriter(myBufOut);
                    char[] buf = new char[SystemDetails.BUF_SIZE];
                    int numRead;
                    while ((numRead = myIn.read(buf)) >= 0) {
                         out.write(buf, 0, numRead);
               } catch (IOException e) {
                    myLog.log(Level.FINE, "Error retrieving output.", e);
                    PrintWriter pw = new PrintWriter(out);
                    e.printStackTrace(pw);
               } finally {
                    Helpers.close(out);
     }///:>
}///:~

Similar Messages

  • How can I execute an external program from within a button's event handler?

    I am using Tomcat ApacheTomcat 6.0.16 with Netbeans 6.1 (with the latest JDK/J2EE)
    I need to execute external programs from an event handler for a button on a JSF page (the program is compiled, and extremely fast compared both to plain java and especially stored procedures written in SQL).
    I tried what I'd do in a standalone program (as shown in the appended code), but it didn't work. Instead I received text saying the program couldn't be found. This error message comes even if I try the Windows command "dir". I thought with 'dir' I'd at least get the contents of the current working directory. :-(
    I can probably get by with cgi on Apache's httpd server (or, I understand tomcat supports cgi, but I have yet to get that to work either), but whatever I do I need to be able to do it from within the button's event handler. And if I resort to cgi, I must be able to maintain session jumping from one server to the other and back.
    So, then, how can I do this?
    Thanks
    Ted
    NB: The programs that I need to run do NOT take input from the user. Rather, my code in the web application processes user selections from selection controls, and a couple field controls, sanitizes the inoputs and places clean, safe data in a MySQL database, and then the external program I need to run gets safe data from the database, does some heavy duty number crunching, and puts the output data into the database. They are well insulated from mischeif.
    NB: In the following array_function_test.pl was placed in the same folder as the web application's jsp pages, (and I'd tried WEB-INF - with the same result), and I DID see the file in the application's war file.
            try {
                java.lang.ProcessBuilder pn = new java.lang.ProcessBuilder("array_function_test.pl");
                //pn.directory(new java.io.File("K:\\work"));
                java.lang.Process pr = pn.start();
                java.io.BufferedInputStream bis = (java.io.BufferedInputStream)pr.getInputStream();
                String tmp = new String("");
                byte b[] = new byte[1000];
                int i = 0;
                while (i != -1) {
                    bis.read(b);
                    tmp += new String(b);
                getSelectionsDisplayTextArea().setText(getSelectionsDisplayTextArea().getText() + "\n\n" + tmp);
            } catch (java.io.IOException ex) {
                getSelectionsDisplayTextArea().setText(getSelectionsDisplayTextArea().getText() + "\n\n" + ex.getMessage());
            }

    Hi Fonsi!
    One way to execute an external program is to use the System Exec.vi. You find it in the functions pallet under Communication.
    /Thomas

  • How Can I execute an external program from my vi?

    Hi guys,
    I want to execute a external program to use it when i called with a bottom. I want push a bottom and execute the program, like acess direct icon or so.
    Any help?.

    Hi Fonsi!
    One way to execute an external program is to use the System Exec.vi. You find it in the functions pallet under Communication.
    /Thomas

  • How To Run An External .exe File With Command Line Arguments

    Hiya, could anyone tell me how I can run an external .exe file with command line arguments in Java, and if possible catch any printouts the external .exe file prints to the command line.
    Thanks.

    Using the Runtime.exec() command. And read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • How to Run External Exe/Scripts

    Hi,
    I am new to Java. I am doing a GUI Application Using Swing. I want to execute list of external exe or perl script repeatedly from my Application. I Tried that one using in for loop. within the for loop i write execute my external exe or script. I got the expected result. but my problem is I can not interact with the application on the of loop execution. Any one can Give me a Solution?.
    Here is my Try..
    Runtime rt = Runtime.getRuntime();
    Process pr ;
    String ScriptPath
    for (int rcount = 0; rcount < trows ;rcount++ ){
         ScriptPath = "D:/Scrip" + rcount + ".pl";
         try{
              pr = rt.exec(ScriptPath);
              exitVal = pr.waitFor();
         catch (Exception e){
              exitVal = 4;
         JOptionPane.showMessageDialog(null, "Status: " + exitVal, "Status" , JOptionPane.ERROR_MESSAGE);
    Thanks,
    Rajesh.K

    You are probably executing you external apps via the Event Dispatch Thread. This is the thread responsible for updating the GUI.
    You need to read up on the SwingWorker class. This is exactly where it should be used.
    http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
    nes

  • Starting an external .exe application from within Visual Basic

    How do I start an external .exe appliction from within Visual Basic. for example start Internet Explorer or FireFox?
    Thanks in advance
    Big Buzzard
    Philippe de Marchin

    How do I start an external .exe appliction from within Visual Basic. for example start Internet Explorer or FireFox?
    If you know the path and filename of the application, or if it is an application that the operating system will find for you, then you can pass the application details to the Start method of the Process class.   If you don't know the path and filename
    of the application - for instance you want to start the user's web browser but it might be IE or Firefox or something else, then the argument to the Start method can be of any file type for which the extension has been associated with an application installed
    on the system. 
    https://msdn.microsoft.com/en-us/library/53ezey2s(v=vs.110).aspx

  • How to execute external exe in SSIS Package

    Hi,
    I wanted to know how to execute external exe from SSIS Package can any one explain me or provide me valuable links.
    Regards ,
    Ajay

    There are few things you need to take care before executing exe from SSIS
    1. The arguments etc expected by exe should be clearly defined inside execute process task
    2. The Path where exe exists should be accessible to the account executing the package. SO you should grant account required permissions
    3. If executing from a job make sure you either define a proxy account with required permissions and configure it to run the job or give service account all access required for executing exe
    see
    http://www.mssqltips.com/sqlservertip/2163/running-a-ssis-package-from-sql-server-agent-using-a-proxy-account/
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • How to run an external .exe file from an indesign pluging

    Hi,
          Suppose if I have written an separate application in C++ (.exe file) & need to run it from an indesign pluging(as if a service in windows). have you provided that facilities in your SDK? if it's please let me know how to run an external .exe file from a indesign pluging.
    Thanks,

    I'm actully writing data in PMString to a external txt file.
    another question..
    if i want to execute an action when the ok button is cliked how can i do it?
    whe i add a button(widget) i know how to handle it. please see my code.
    // Call the base class Update function so that default behavior will still occur (OK and Cancel buttons, etc.).
    CDialogObserver::Update(theChange, theSubject, protocol, changedBy);
    do
    InterfacePtr<IControlView> controlView(theSubject, UseDefaultIID());
    ASSERT(controlView);
    if(!controlView) {
    break;
    // Get the button ID from the view.
    WidgetID theSelectedWidget = controlView->GetWidgetID();
    if (theChange == kTrueStateMessage)
    //if (theSelectedWidget == kEXTCODGoButtonWidgetID
    switch(theSelectedWidget.Get())
             case kEXTCODGoButtonWidgetID:
      this->ViewOutput();
      break;
             case kEXTCODFindButtonWidgetID:
      this->SaveLog();
      break;
    // TODO: process this
    } while (kFalse);
    I do two actions "SaveLog" & "ViewOutput()" using two buttons. But i dont know how to execute an action when the ok button is clicked...

  • How can I execute external application?

    Hi friends I want printing my barcodes a laser printer (Kyocera) it isn't a barcode printer. So I think (and I look kyocera web page my model doesn't support barcode printing in sap) print my barcodes using an external system. Before SAP we are using JollyPrint application for printing barcodes. It is using an Excel file.
    I can create a excel file for this application. I must execute this (JollyPrint-it is a label application) application when I press a button. How can I execute this application?
    Thanks
    Mehmet
    P.S. I have been writing this message with details may be somebody can give me a simple way for this

    Well, I can suggest you following steps. May be it works for you .
    -Create an external OS command in SM69
    -Test OS command in SM49 ( <u><i>about OS command if you search in SDN you’ll get lot of material</i></u> )
    -Create a Script at your OS level, I’m assuming you might have some UNIX flavor or Sun solaria’s.
    -Create a Shell script , which execute the printer job from OS .
    -Shell script will have parameters . ( e.g. printer name, destination etc )
    -set the path of shell script directory in SM69 ( the command you just created )
    -Execute shell script using your ABAP program ( use FM "SXPG_COMMAND_EXECUTE" )
    In the ABAP  program you can pass the parameters and execute the command from ABAP as a result your job will start printing on the required destination. Moreover, you can also capture the spool at OS level .
    FYI
    For UNIX script, if you search in www.google.com ( UNIX forums) . you’ll get shell script .
    Hope this’ll give you idea!!
    <b>P.S award the points.</b>
    Good luck
    Thanks
    Saquib Khan
    "Some are wise and some are otherwise"

  • How can an add-on like Firesheep access and execute an external program like Winpcap? Is that a security flaw in Firefox?

    I have been reading about the Firesheep add-on that allows the user to hijack sessions of users on the network by stealing the cookie. I understand that to prevent any application from stealing the cookie, the cookie should not be passed by the site without SSL. However, my understanding of how Firesheep works is that it interfaces with Winpcap (a network sniffer). So my question is "How can an add-on execute an external program or operating system command like Winpcap?" Can any add-on do this and should I be extremely afraid of downloading any add-on because of the potential that it could have complete access to my system?

    Hi Scott-L.
    You asked a very good question and it turns out you're right.
    However, one must be aware that download an Addon on another website that Mozilla may be dangerous. Indeed, the Addons found on the Addon Center are checked (roughly).
    In addition, Firefox includes a blacklist that blocks addons identified as malicious.
    More information here: [http://www.computerworld.com/s/article/9193420/Mozilla_No_kill_switch_for_Firesheep_add_on?taxonomyId=17&pageNumber=1]

  • How can I call external exe in java

    Hi ,
    Is It Possible to call external exe in java.
    I read Runtime.exe("some exe") but actually my exe expects some input to process for that how can i pass the input to my exe and how can get the response from exe to my java class.
    any sample code is welcome.
    Thanks
    Babu H

    example
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.io.*;
    public class RuntimeExample extends JFrame {
        private JTextArea textArea;
        private JTextField textField;
        private PrintWriter writer;
        public RuntimeExample()
            init();
            initProcess();
        public void init()
            textArea = new JTextArea(20, 80);
            textArea.setEditable(false);
            textField = new JTextField(30);
            textField.addKeyListener(new KeyAdapter()
                public void keyPressed(KeyEvent event) {
                    if (event.getKeyCode() == KeyEvent.VK_ENTER)
                        if (writer != null)
                            textArea.setText("");
                            writer.print(textField.getText() + "\r\n");
                            writer.flush();
                            textField.setText("");
            Container container = getContentPane();
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setViewportView(textArea);
            container.add(scrollPane, BorderLayout.CENTER);
            container.add(textField, BorderLayout.SOUTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            textField.grabFocus();
            setVisible(true);
        public static void main(String[] args) {
            new RuntimeExample();
        public void initProcess()
            Runtime rt = Runtime.getRuntime();
            try
                //Process p = rt.exec(new String [] {"cmd", "/C", textField.getText()});
                //textArea.setText("");
                //textField.setText("");
                Process p = rt.exec("cmd");
                writer = new PrintWriter(p.getOutputStream());
                Thread thread1 = new Thread(new StreamReader(p.getErrorStream()));
                Thread thread2 = new Thread(new StreamReader(p.getInputStream()));
                thread1.start();
                thread2.start();
                System.out.println("Exit Value = " + p.waitFor());
            catch (Exception ex)
                textArea.append(ex.getMessage());
                ex.printStackTrace();
        public class StreamReader implements Runnable
            InputStream is;
            public StreamReader(InputStream is)
                this.is = is;
            public void run()
                try
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String data;
                    while ((data = reader.readLine()) != null)
                        textArea.append(data + "\n");
                    reader.close();
                catch (IOException ioEx)
                    ioEx.printStackTrace();
    }you can pass input to the exe by using getOutputStream() from Process and get the output from getInputStream() from Process

  • How to execute an external file in java ?

    How to execute an external file , where the file name of the external file is in unicode character. (i,e, may be in Chinese character).

    Process p = Runtime.getRuntime().exec("/path/to/executable");
    This is write. But my question is while the file name is in Chinese font.
    It means while a file name is in Chinese font or any unicode character that are supported by window but not in the command prompt. In this case the file name is changed to ??????.doc like.
    So, while trying to execute this it shows File not found message.

  • How to create a button in a interactive document and use the button to launch and external "exe." file.

    I created an interactive document and will export as a swf.  I would like to create a button in the interactive document to launch and external "exe." file. Is this possible.

    You will need to create custom web part editor. Look at the following example. It also have added button and its events. I am sure you can use this sample as base and code your logic.
    http://msdn.microsoft.com/en-us/library/hh228018(v=office.14).aspx
    Amit

  • How to execute an external executable in my java program?

    hi,
    i want to write a java program to execute some external executables.
    for example, i had an executable which takes a string as its input parameter, and:
    it writes to stdout a string : "[stdout] hello, "+parameter+"!";
    it writes to stderr a string : "[stderr] hello, "+parameter+"!".
    and it exits with an error code 1.
    my java program looks like this:
    public class Test {
      public static void main(String[] args)
      throws Exception {
        String inputParameter = "heavyz";
        String stdoutOutput = null;
        String stderrOutput = null;
        int exitCode;
        // Do something here to launch the executable,
        // providing inputParameter as its input,
        // getting its stdout output to String stdoutOutput,
        // and its stderr output to String stderrOutput,
        // and its exit code to int exitCode.
        return;
    }anybody can help me to complete the program above?
    thanks a lot.
    heavy ZHENG

    check out Runtime.getRuntime().exec();

  • How do I call an external program

    From within my Java program I want to execute an
    external program and dump the output into a string
    or array of strings. In perl this is trivial $a=`dir`.
    How do I do it in Java?
    Thanx,
    Art.

    with Runtime
                try {
                        Process p = Runtime.getRuntime().exec("cmd.exe /c dir");
                        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        String str = "";
                        while((str = in.readLine()) != null)
                            //do what you want to with input
                        in.close();
                    catch(Exception e)
                        e.printStackTrace();
    [/code[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Firefox 3.6.8 won't open local php files. It opens the save as text dialog box instead.

    When I try to open a local php file on my MAC hard drive with FF 3.6.8, the save file dialog box opens instead. It says: You have chosen to open index.php which is a TextEdit.app Document. I do not have this problem with Firefox 3.5.11. I have tried:

  • Questions on B2B Integration

    We are evaluating B2B Integration for one of our Peer to Peer B2B projects using RosettaNet v1.1. I have reviewed most of the online docs to gain knowledge on how the product works. I plan on running the examples pretty soon. I need answers to a coup

  • Daily Sales Outstanding Report : Customer Exit or Formula

    Hello All, I am working on Daily Outstanding Report which is on 0FIAR_C02 Cube. in this cube i have 4 key figures 0DEBIT, 0CREDIT, 0BALANCE, 0SALES. There is one standard query 0FIAR_C02_Q1001 where i enter value for 0FISCAL YEAR / PERIOD = 009.2009

  • CCtr line item table

    Hi, Apart from CO line item table which is COEP, is there a table which is specific for cost center line items ? Thanks for your response

  • Tags in JCAPS 5.1.3

    Hi everyone! I'm trying to understand the usage of the tag in JCAPS 5.1.3 I've tagged several components (a subproject) from a proyect and I want to know if a can: 1) export only the tagged components? 2) retrieve all the tagged components at the sam