Interact with exe in java

Hi!
I got a old exe file, that no more maintain by any team.
Unfortunately, requirement has it that I need to run this exe, do some interaction, such as "enter" and "wait" and "input value", get "value"
And it has to be retrive by java,
can anyone give idea how should this done?
I know I can excute this program, but I don't know how to fetch the program any more key board input...
Thanks

What sort of exe?
If it is a GUI, then you will need to use JNI to interact with it. You might find a 3rd party tool that already does this for the GUI/OS that you are targetting. If not you have to write it yourself.
If it is a command line application then you can use Runtime.exec(). That creates a process without output and input streams. The input stream allows you to send text to the process.

Similar Messages

  • Interacting with Powershell from Java

    Hi,
    I'm trying to run a Java application which creates a new powershell process on startup and then later on interacts with it multiple times. Calling powershell.exe and have it execute a single command and return the output works fine for me. The problem arises if I don't want the powershell process to immediately finish/exit but to stay open so I can write to its outputStream and receive results back from the inputStream.
    String input = "dir";
    String[] commandList = {"powershell.exe", "-Command", "dir"};
    ProcessBuilder pb = new ProcessBuilder(commandList);
    Process p = pb.start();
    if(input != null) { 
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
    writer.println(input);
    writer.flush();
    writer.close();
    //p.getOutputStream().close();
    Gobbler outGobbler = new Gobbler(p.getInputStream());
    Gobbler errGobbler = new Gobbler(p.getErrorStream());
    Thread outThread = new Thread(outGobbler);
    Thread errThread = new Thread(errGobbler);
    outThread.start();
    errThread.start();
    System.out.println("Waiting for the Gobbler threads to join...");
    outThread.join();
    errThread.join();
    System.out.println("Waiting for the process to exit...");
    int exitVal = p.waitFor();
    System.out.println("\n****************************");
    System.out.println("Command: " + "cmd.exe /c dir");
    System.out.println("Exit Value = " + exitVal);
    List<String> output = outGobbler.getOuput();
    input = "";
    for(String o: output) { 
    input += o;
    System.out.println("Final Output:");
    System.out.println(input);
    This code returns the result of the "dir" command from a powershell - fine. But as you can see, I'm trying to run a second "dir" command using
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
    writer.println(input);
    writer.flush();
    This has no effect whatsoever - no second dir output is shown when I run my code. I've also experimented with a powershell.exe option to open the powershell but not close it immediately:
    String[] commandList = {"powershell.exe", "-NoExit", "-Command", "dir"};
    But then my code hangs, meaning the Gobbler's who consume the process's inputStream don't read anything - strangely enough: they don't even read the first line - there must be at least some output....
    I've also tried to close the process's outputStream after writing the second "dir" command to it - didn't change anything.
    But when I initially call the cmd.exe using the /k (keep open) switch:
    String[] commandList = {"cmd.exe", "/k", "dir"};
    I can then still write to that outputstream and invoke the second "dir" command and get the output of both "dir" commands from the inputstream fo that process.
    Any help is highly appreciated.
    Thanks
    Kurt

    user4491593 wrote:
    BUT: my Gobblers only read the output of all my commands Then why don't change your Gobbler code ? ;)
    Test this, it's ugly and needs improvemens, but by now works fine on linux and windows:
    public class Gobbler implements Runnable {
        private PrintStream out;
        private String message;
        private BufferedReader reader;
        public Gobbler(InputStream inputStream, PrintStream out) {
            this.reader = new BufferedReader(new InputStreamReader(inputStream));
                   this.out = out;
            this.message = ( null != message ) ? message : "";
        public void run() {
            String line;
            try {
                while (null != (line = this.reader.readLine())) {
                    out.println(message + line);
                this.reader.close();
            } catch (IOException e) {
                System.err.println("ERROR: " + e.getMessage());
    public class PowerConsole {
        private ProcessBuilder pb;
        Process p;
        boolean closed = false;
        PrintWriter writer;
        PowerConsole(String[] commandList) {
            pb = new ProcessBuilder(commandList);
            try {
                p = pb.start();
            } catch (IOException ex) {
                throw new RuntimeException("Cannot execute PowerShell.exe", ex);
            writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
            Gobbler outGobbler = new Gobbler(p.getInputStream(), System.out);
            Gobbler errGobbler = new Gobbler(p.getErrorStream(), System.out);
            Thread outThread = new Thread(outGobbler);
            Thread errThread = new Thread(errGobbler);
            outThread.start();
            errThread.start();
        public void execute(String command) {
            if (!closed) {
                writer.println(command);
                writer.flush();
            } else {
                throw new IllegalStateException("Power console has ben closed.");
        public void close() {
            try {
                execute("exit");
                p.waitFor();
            } catch (InterruptedException ex) {
        public static void main(String[] args) throws IOException, InterruptedException {
            /*   PowerConsole pc = new PowerConsole(new String[]{"/bin/bash"});
            PowerConsole pc = new PowerConsole(new String[]{"/bin/bash"});
            pc.execute("pwd");
            pc.execute("ls");
            pc.execute("cd /");
            pc.execute("ls -l");
            pc.execute("cd ~");
            pc.execute("find . -name 'test.*' -print");
            pc.close();
            //      PowerConsole pc = new PowerConsole(new String[]{"cmd.exe"});
            PowerConsole pc = new PowerConsole(new String[]{"powershell.exe", "-NoExit", "-Command", "-"});
            System.out.println("========== Executing dir");
            pc.execute("dir");
            System.out.println("========== Executing cd\\");
            pc.execute("cd \\"); Thread.sleep(2000);
            System.out.println("========== Executing dir");
            pc.execute("dir"); Thread.sleep(2000);
            System.out.println("========== Executing cd \\temp");
            pc.execute("cd \\temp"); Thread.sleep(2000);
            System.out.println("========== Executing dir");
            pc.execute("dir"); Thread.sleep(2000);
            System.out.println("========== Executing cd \\bubba");
            pc.execute("cd \\bubba"); Thread.sleep(2000);
            System.out.println("========== Exiting .... bye.");
            pc.close();
    }I tested this and there is still a little problem -look at the test below.
    It seems that when thecommand
    executed in the powershell prints only a one ot two lines,
    powershell doesn't flush the output stream
    .... but this rather problem of powershell, not the java code
    I have not a clue how to force powershell to flush
    it's output stream after each command.
    C:\temp>java -jar PowerShell.jar
    ========== Executing dir
        Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp
    Mode                LastWriteTime     Length Name
    -a---        2012-01-09     01:16       5290 PowerShell.jar
    ========== Executing cd\
    ========== Executing dir
        Directory: Microsoft.PowerShell.Core\FileSystem::C:\
    Mode                LastWriteTime     Length Name
    d----        2012-01-08     02:56            61587b977687a6e22fbe
    d----        2011-12-14     03:19            Documents and Settings
    d----        2011-12-15     00:05            oraclexe
    d-r--        2012-01-08     03:44            Program Files
    d----        2012-01-05     19:59            sqldeveloper
    d----        2012-01-09     01:15            temp
    d----        2012-01-09     01:13            WINDOWS
    -a---        2011-12-14     03:12          0 AUTOEXEC.BAT
    -a---        2011-12-14     03:12          0 CONFIG.SYS
    ========== Executing cd \temp
    ========== Executing dir
        Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp
    Mode                LastWriteTime     Length Name
    -a---        2012-01-09     01:16       5290 PowerShell.jar
    ========== Executing cd \bubba
    Set-Location : Cannot find path 'C:\bubba' because it does not exist.
    At line:1 char:3
    + cd  <<<< \bubba
    ========== Exiting .... bye.
    C:\temp>

  • Interacting with perl through java.

    I'm trying to do something with Java that I haven't managed to do until now. I'm trying to interact with a perl process giving him input and reading output.
    I have a perl module that has several functions and the idea is to launch a process in a java program with the following line :
    perl -e 'while(<STDIN>) { eval $_ ; }'
    and then give the process the necessary input and the read the given output.
    For instance with the above line you can do the following:
    [user@host ~]$ perl -e 'while(<STDIN>) { eval $_ ; }'
    print "Hello World\n";
    Hello World
    Here is the code I'm using:
    import java.io.BufferedReader;
    public class ExecProgram {
    private static Runtime runtime;
    private static Process process;
    public static void main(String[] args) {
         runtime = Runtime.getRuntime();
         try {
         process = runtime.exec("/usr/bin/perl -e 'while(<STDIN>) { eval $_ ; }'");
              process = runtime.exec(cmd);
         } catch (IOException e) {
              System.err.println("Error executing process");
         PrintWriter out = new PrintWriter(process.getOutputStream());
         String commandLine = "print \"Hello World\n\"";
         out.println(commandLine);
         BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
         try {
         String line;
         while ((line = in.readLine()) != null)
              System.out.println("Output: "+line);
         } catch (IOException e) {
         System.err.println("Error reading output");
    As you can see I'm using Runtime class to interact with the process but nothing happens if replace the exec line with:
    process = runtime.exec("ls");
    I can see in the output the listing of the current directory.
    Have you ever tried something like this? Is this the correct way for doing this?

    Have you ever tried something like this? I have. Here's a rough sample:
        public static void main(String[] args) throws Exception {       
            String[] cmd = new String[]{
                "/usr/bin/perl",
                "-e",
                "while(<>){ eval or die $@; }"
            final Process p = Runtime.getRuntime().exec(cmd);
            new Thread(){
                public void run(){
                    try{
                        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        for(String line; (line = r.readLine()) != null; System.out.println("ProcessOUT:: "+line));
                    catch (Throwable t){
    //                    t.printStackTrace();
            }.start();
            new Thread(){
                public void run(){
                    try{
                        BufferedReader r = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                        for(String line; (line = r.readLine()) != null; System.err.println("ProcessERR:: "+line));
                    catch (Throwable t){
    //                    t.printStackTrace();
            }.start();
            new Thread(){
                public void run(){
                    try{
                        OutputStream out = p.getOutputStream();
                        for(int ii = 0; ii < commands.length; ii++){
                            System.err.println("Sending command: "+commands[ii]);
                            out.write(commands[ii].getBytes());
                            out.write('\n');
                            out.flush();
                    catch (Throwable t){
    //                    t.printStackTrace();
            }.start();
            int exit = p.waitFor();
            System.err.println("Process exited with code: "+exit);
        static final String[]
            commands = {
                "print \"The road goes ever\\n\";",
                "print \"ever\\n\";",
                "print \"on.\\n\";",
                "exit 13;"
        ;

  • Interacting with cmd.exe

    Hi all,
    i dunno if this has been asked before, but my problem is to let the user interact with an executable ran via "cmd.exe /c executable".
    i have an executable program that awaits a response from the user, but when i used the Streams provided by java.lang.Process after many scenarios i noticed that the process inputStream provides me with the output only when the program is finished, while it returns no text while the program is waiting for response
    as an example, my problem looks like :
    try {
                Process p = Runtime.getRuntime().exec("cmd.exe /c mysql -u toto");
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(p.getInputStream()));
                  String s = null;
                while ((s = reader.readLine()) != null) {
                        System.out.println(s);
    } catch (IOException ex) {
                ex.printStackTrace();
    }the mysql command would show "enter password : " or something like that, but this program will not show it...unless the mysql is finished
    any ideas? thanks :)

    that's right, i tried to look for classes that provide "live streams" in java.io ... i thought the PipedReader and PipedWriter could do it, but i need to get the program's reader and writer for this (and i don't know how to do that...) or maybe those classes are unnecessary and there is another way to do it?

  • Interactive .exe in Java

    Hi I have a interactive .exe program which I want to incorporate into Java Runtime. How do I go about it ?
    Sudhakar

    Using Runtime.exec("yourprogram.exe") to execute the program.
    it will return a process object.
    get the inputstream from the process returned (this is the program output)
    and the outputstream (the program input)
    interact with your exe program using the inputstream and outputstream

  • Interacting with MS Word through Java

    Hi friends,
    How to interact with a MS Word file through the java program. please send me some sample codes. Thanks in advance.....
    Regards,
    Prakash.....

    Prakashjava wrote:
    Hi friends,
    How to interact with a MS Word file through the java program. please send me some sample codes. Thanks in advance.....
    Can't be done in pure Java.

  • Java interaction with websites?

    Hey,
    I'm been learning java for a few months now, and know the basics well, I have written a few small programs, including one which transfers songs from iPod to computer.
    I need some advice on where to start on my next project. Basically I want to make a program which automatically performs tasks in the background on websites, for example listing an item on ebay, or uploading a video to youtube. And I'd also like it to read information from different pages, so that I could maybe gather a database of prices from ebay, or somthing along those lines.
    Which classes could I use java to interact with html?
    Where do I start? :)
    My java vocabulary isn't great yet ;)

    Ryanz wrote:
    Ok ... I'm checking it out at the moment, are there any other maybe simpler ways? Or can somone explain how to get the JAX-WS installed and ready to use with eclipse?Ryanz,there are few things involved here.
    1).First and foremost you need to findout whether if respective website offers you any kind of Web-Services to serve your cause.
    Just as an example eBay offers set of services to serve your cause to know more about this you can visit the below links
    [http://www.xml.com/pub/a/2005/09/28/ebay-metadata-web-services.html]
    [http://developer.ebay.com/community/featured_projects/default.aspx?name=Code%20Samples%20Project]
    Similarly identify whether if respective other focused webservice providers offer any specific services serving your cause.
    2).Analyse their service specifications
    3).Identify and Plan for list of Data Transfer Objects to which we can bind this service
    4).Implement for a Stub (may be using Apache Axis) or use JAX-RPC or use JAX-WS or any other related technologies to implement your Webservice Client.
    Coming back to using tools like Apache Axis,JAX- RPC or JAX-WS.
    you might be intrested in looking towards the below set of turtorials
    [http://www.onjava.com/pub/a/onjava/2002/06/05/axis.html]
    [http://www.ibm.com/developerworks/webservices/library/ws-castor/]
    [http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXRPC.html]
    [http://www.ibm.com/developerworks/edu/j-dw-java-jaxrpc2-i.html]
    [http://java.sun.com/webservices/docs/2.0/tutorial/doc/]
    [http://www.myarch.com/create-jax-ws-service-in-5-minutes]
    It is not nessary that a provider has to provide relvant data in form offering webservices and sometimes they can offer you different specs which could be Like regular Java RMI services or DCOM object or something like Feeds(RSS 2.0/ATOM) for providing Latest updates on your account.I'd say it'd be more work for us to identify what kind of service the provider is provding us and how best make use of it so that we can use the relavant data in our application.
    and believe me in most of the cases only point 4 changes after going through point 1,2 & 3.
    Hope that helps :)
    REGARDS,
    RaHuL

  • Description: A problem caused this program to stop interacting with Windows. Problem signature: Problem Event Name: AppHangB1 Application Name: firefox.exe Application Version: 1.9.2.3855 Application Timestamp: 4c48d5ce Hang Signature: 9962

    I am having this problem, in the first window when I try to do anything.
    Description:
    A problem caused this program to stop interacting with Windows.
    Problem signature:
    Problem Event Name: AppHangB1
    Application Name: firefox.exe
    Application Version: 1.9.2.3855
    Application Timestamp: 4c48d5ce
    Hang Signature: 9962
    Hang Type: 0
    OS Version: 6.0.6002.2.2.0.768.3
    Locale ID: 1033
    Additional Hang Signature 1: 5df72ce88195c0212c542e9c8c172716
    Additional Hang Signature 2: 2b94
    Additional Hang Signature 3: 9acafbb8ad01bf9d2eb258d8fddad3ca
    Additional Hang Signature 4: 9962
    Additional Hang Signature 5: 5df72ce88195c0212c542e9c8c172716
    Additional Hang Signature 6: 2b94
    Additional Hang Signature 7: 9acafbb8ad01bf9d2eb258d8fddad3ca
    == This happened ==
    Every time Firefox opened
    == User Agent ==
    Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4

    I suspect a RAM or hardware problem.

  • Pacman frontend in Java - Howto interact with alpm

    I plan to write a(nother :-) ) GUI frontend to Pacman using Java + Swing.  However I need some advice regarding how should I interact with Pacman.
    Basically my requirements are:
    1.  Reading/Searching package database
    2.  Showing a download progress bar
    3.  Showing a progress bar when Pacman is installing/removing package(s)
    As 'alpm' is a C library it's not easily accessible from Java.  The only and perhaps dummest solution that I can think of is to write my own pseudo-alpm library to handle the requirements but I'd seriously rather avoid the re-work and bugs of such a process.  Is there any other way?
    I'd appreciate any idea/hint.  TIA,
    Bahman

    If you have some success creating jni bindings to libalpm you might consider creating an AUR package to join the lua, perl and python packages that are there now.

  • The program shany ip surrvilance Playback.exe version 4.0.7.3 stopped interacting with Windows and was closed

    in windows server 2008 r2 running shany ip surveillance
    when i want to playback from record file windows encounter error:The program shany ip surrvilance Playback.exe version 4.0.7.3 stopped interacting with
    Windows and was closed

    Hi Koosha,
    You should ask this question on
    Windows Forums.
    Thanks!
    If this answers your question please mark as answer. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

  • Can a java code interact with trigger

    Hi guyz ,
    is there any way by which a trigger can interact with JDBC ?
    I want to check the database each time its updated and if some condition is violated , the info((row from table which has voilated some rule) is passed to java code which can then take necessary action . Can anyone help me out in this because i am not aware of any way by which a trigger can interact with java code .
    Regards,
    Nikhi

    nikhil456123 wrote:
    Hi guyz ,
    is there any way by which a trigger can interact with JDBC ?
    I want to check the database each time its updated and if some condition is violated , the info((row from table which has voilated some rule) is passed to java code which can then take necessary action . Can anyone help me out in this because i am not aware of any way by which a trigger can interact with java code .Note that even though it might be possible you might want to consider that it isn't necessarily a good idea.
    Say the action is "send email". Then every time an insert/update/delete occurs then an email is sent. That would obviously slow down those operations a lot. Not to mention that if 1000 inserts occur then someone is going to get 1000 emails.
    There can be alternatives that are much better.

  • OUTLOOK.EXE version 12.0.6668.5000 stopped interacting with Windows and was closed.

    I have an end user whose Outlook 2007 is spontaneously closing. It will enter a 'not responding' state and then shut down (and sometimes relaunch). In going through the event log the following information was obtained. O/S is Win-7, 64-Bit. Any input greatly
    appreciated.
    The program OUTLOOK.EXE version 12.0.6668.5000 stopped interacting with Windows and was closed. To see if more information about the problem is available, check the problem history in the Action Center control panel.
    Process ID: 14ac
    Start Time: 01cf6af126c3ad83
    Termination Time: 79
    Application Path: C:\Program Files (x86)\Microsoft Office\Office12\OUTLOOK.EXE
    Report Id: c7d7556f-d9dd-11e3-a17c-2cd05a89d710
    And further into the Event Log (Application)
    - System
    - Provider
    [ Name] Application Hang
    - EventID 1002
    [ Qualifiers] 0
    Level 2
    Task 101
    Keywords 0x80000000000000
    - TimeCreated
    [ SystemTime] 2014-05-12T14:03:22.000000000Z
    EventRecordID 26088
    Channel Application
    Computer uswal-3PLSJX1.amer.thermo.com
    Security
    - EventData
    OUTLOOK.EXE
    12.0.6668.5000
    14ac
    01cf6af126c3ad83
    79
    C:\Program Files (x86)\Microsoft Office\Office12\OUTLOOK.EXE
    c7d7556f-d9dd-11e3-a17c-2cd05a89d710
    55006E006B006E006F0077006E0000000000
    Binary data:
    In Words
    0000: 006E0055 006E006B 0077006F 0000006E
    0008: 0000
    In Bytes
    0000: 55 00 6E 00 6B 00 6E 00 U.n.k.n.
    0008: 6F 00 77 00 6E 00 00 00 o.w.n...
    0010: 00 00 ..

    Hi,
    The event log in your posting is a general error event which occurs when application stops responding. Please make sure the latest patches and service packs are installed for your Outlook 2007.
    Please also restart Outlook in safe mode(Start > Run, type Outlook /safe and Enter) to check whether Outlook 2007 is still not responding or not.
    Thanks,
    Winnie Liang
    TechNet Community Support

  • Using java to interact with a website

    I'm looking to build a program that will function as an alternate front end for an online database so that users can perform batched operations. Is there a way to have java navigate and interacte with a website? This would be something a macro would do, except that I need to be able to interact with the desktop, among other things. Also, I'm stuck with internet explorer, as the IT people don't want Firefox on any of the machines, so that excludes the iMacros add on.
    anyone got an idea? thanks

    DrClap wrote:
    Unless you also control the website. However, even in that case I think that web services are superior in the long run to HTML-scraping.Agreed. I was assuming that if the website was one's own, one wouldn't resort to scraping, but you're right, that needs to be stated.

  • How to interact with a COM component from a Java class

    Hi, could someone give a hint on what API I should explore in order to interact with a COM component from a Java class?
    Thanks in advance
    Luis

    jacob sounds nice...http://danadler.com/jacob/

  • To Interact With Printer

    hi people
    i want to interact with printer . My Problem is i have given the .exe file tht does the job of prining the .pdf files.. i neeed to check weather the printer is working properly and i have to handle the excpetion tht comes from the printer.. can we implement this...
    this is urgent ....

    Let me see if I have the correct spin on what you want to do...
    You have an exe that you have to hand a PDF off to from your Java applicatons.
    You need to check if the printer is working.
    If the printer is not working you need to handle the exception that it will return.
    Since you have an EXE i will assume you are in windows....
    You'll need to check the printer first to see if it works and handle the appropriate exceptions, then I will assume also (my crystal ball is vague this morning) that you will be calling the exe with a cmd and using a command line argument for the PDF and once the print is done, the exe will terminate.
    If not then you will have to build an OLE/DDE interface in JNI depending on what your EXE will support.
    Can you implement this? I don't know, post some of your code and let's see where you have problems and be specific with questions... other wise if you are looking for someone to code it for you... then contact one of your local consulting firms, I'm sure they can get if for you.

Maybe you are looking for

  • User Exit or Badi for AS01 at save.

    Hello! I need a user exit or badi to validate fields from ANLA and ANLZ tables in AS01 trasaction. This validation is before save. I have already check this user exit with no success: AAPM0001        Integración contabilidad activos fijos/mantenimien

  • When I ask for a PDF file to be downloaded using FIREFOX it opens MIcrosoft Word.... in Japanese, I am not kidding!!

    It does not happen in Chrome or Internet Explorer but I don't normally use them. I have done all the things they tell you to do, to set the default as Corel Fusion. I even went so far as to remove Fusion and try setting default at Adobe. It didn't st

  • Can't send texts until iPhone is powered off.

    For the past 3 mornings, I have had to power off my iphone4 before sending any texts. I don't know of it's just iMessage or any texts. I've tried sending iMessage and it won't send unless I power it off and let it reboot.

  • Creating Folder for Existing Folders

    Is it possible to create a new folder for AR for iOS so that you can move already existing folders into it? My folders have become a bit cluttered as I had to create more for specific files, but they should all be filed under another bigger folder. T

  • How to trigger tRFC queue in Transacation SMQ1

    Hi experts, How can I setup a queue table, if any field changed in this table, it will trigger tRFC in transacation SMQ1. Eg. Set JEST table changes can be captured in SMQ1. Thanks ! Looking forward for replying...