Executing bat file without using Runtime.exec()??

Hi all
From my java App ,I am running a bat file. This is what I did:
When I press 'execute' button inside my App, it runs a bat file through Runtime.exec() method. Since exec() runs it through cmd.exe, get a DOS window when I press Execute button. If I manually runs my app from command promt , I dont get it. But I have to create a short cut of my main class in the desktop. This is happening when I run my app from desktop icon.
Now I want to eleminate DOS popup everytime I press execute button. Would anyone pls give an idea how to run bat file without using Runtime.exec()? Any suggestion will be helpful.
Thanks

jscell
Thanks for taking time to answer to my problem .
Here is what my problem: I create a shortcut of my main class in the desktop. Through this shortcut ,I run my java App. My App has a execute button, When I press this button , It run another bat file through Runtime.exec() method, and show some result in the result PAnel. NOw what happen , I get a DOS command window , everytime I press execute button. , Which is very annoying . But If I run my App thorugh command promt by executing: "java myApp", then I dont get this DOS popup. But I have to create a shortcut in the desktop, so other can use it conveniently.
NOw I am not sure why I am getting this DOS window in the middle of my Application. IS it for using Runtime.exec() method? or for running bat file through my application? Can anyone pls tell me? I am kind of new to java, and I am learning lot of stuff from this forum .
Would u pls suggest me about how to eleminate this DOS popup when I press execute button.
Regrds

Similar Messages

  • Where to put files in using runtime.exec(run.exe)?

    I try to use the following program in EJB to call my EXE program in the J2EE server:
    runtime.exec("c:\\j2ee\\public\\exe\\run.exe temp.txt");
    In the execution of mill_turn.exe, it will open several files for read and write.
    So where to put the file temp.txt and other files the run.exe need to read?
    Looks like the J2EE server can not find them?
    Thanks!

    I got it in Java SE1.4.
    File dir=new File("c:\\j2ee\\public_html\\Mill_turn\\exe\\");
    Process proc = rt.exec(cmd,null,dir);Use above codes, I really got the right output from my external program for the first time. But , after that, the output keeps same when I change the filename in the following code:
    cmd="c:\\..\\run.exe temp.prt"
    to
    cmd="c:\\..\\run.exe Abc1.prt" , which must have different output.
    The codes for calling external program are implemented in the SessionBean of J2EE.

  • Using Runtime.exec to execute a C++ executable

    Hello,
    I would like to know if it possible to execute a C++ executable using Runtime.exec() and wait for it to complete and how do I read back the output file created by the C++ executable into the Java Code?
    TIA.
    RHP

    When I execute the code with Runtime.exec(), and read
    from the Process's inputStream I am ablt to view the
    cout from the C++ code. But the output file that has
    to be created by the C++ code is not created,Then this is maybe an error in the C++ code? Maybe you don't have permissions to create that file where you want to.
    where
    would the output from the C++ code go to when I use a
    ofstream in my C++ code andIf you create the file stream in C++ with an absolute file name then the output goes into that file. If it's a relative file name, then the basis is most likely the current working directory (found in the system property "user.dir" if you used one of Runtime's methods without the File argument, otherwise it's the directory you provide.
    How do I read both streams
    from the Java Code?You create an FileInputStream and - if you want to read character instead of binary data - on top of that an InputStreamReader. You might add a BufferedReader on top of that if you want to read line by line.
    does that answer your questions?
    robert

  • IOException File not found - While using Runtime.exec

    Hey All,
    I have written a Java application which needs to start up another external application. I have executables for that external application for different platforms (Win32, PPC and Linux). When the Java application is started it detects the OS and starts up the right executable according to the OS. The executable loads up fine on Windows without any problems. But in both Linux and Max OS X I get this exception:
    java.io.IOException: java.io.IOException: "/home/vilas/Documents/Project/build/CLISP/linux/lisp.run": not found
            at java.lang.UNIXProcess.<init>(UNIXProcess.java:143)
            at java.lang.Runtime.execInternal(Native Method)
            at java.lang.Runtime.exec(Runtime.java:566)
            at java.lang.Runtime.exec(Runtime.java:428)
            at jplan.communication.lispserver.LispServer.startupServer(LispServer.java:143)
            at jplan.communication.lispserver.LispServer.run(LispServer.java:109)
            at java.lang.Thread.run(Thread.java:534)lisp.run has all the necessary permissions. If I copy the string (/home/vilas/Documents/Project/build/CLISP/linux/lisp.run) and paste it in a terminal and press enter, the application starts up fine without any problems!! Can you please tell me what could be going wrong?
    The following extra information maybe helpfull:
    1) I use the exec(String command, String[] envp, File dir) version of exec.
    2) The complete format of the command is as follows (one long string):
    "/home/vilas/Documents/Project/build/CLISP/linux/lisp.run" -B "/home/vilas/Documents/Project/build/CLISP/linux" -M "/home/vilas/Documents/Project/build/CLISP/linux/lispinit.mem" -i loader.lisp
    Thanks in advance for your time and efforts.

    I found the problem after extensively searing the forums (looking upto page 4 !! of the results). The problem was that I was using quotes to surround the paths in the command. If you copy and paste it in a terminal it will work fine but it does not work with runtime.exec. I am not sure, but I think the reason is that when a terminal is used, some pre-processing of the commands take place before they are passed onto the OS(shell). But while using runtime.exec, that pre-processing is not peformed and therefore some things will not work.
    In order to fix the problem, I use quotes only when the OS is windows. In other cases(OS X, Linux) I escape the spaces i.e. replace " " with "\ ".
    PS: The executable is a binary compiled from C code.

  • Using runtime.exec to zip some files

    Hi,
    I am using runtime.exec to try to automatically zip a bunch of files on a server. However, it does not seem to be working.
    Before I execute the command, I save the zip command in a string. I then print the string to a log file, and then execute the runtime zip command. But nothing happens.
    Yet, when I copy the string from the log, and paste it in a terminal, it properly creates the zip files. So, I know I have the correct command string, it just does not seem to be working within the java application. Also, the command string uses fully qualified directories, so it is not a directory issue.
    I am using ubuntu linux.
    Any ideas?
    -Adam

    adamSpline wrote:
    Hi,
    I am using runtime.exec to try to automatically zip a bunch of files on a server. However, it does not seem to be working.
    Before I execute the command, I save the zip command in a string. I then print the string to a log file, and then execute the runtime zip command. But nothing happens. Within Runtime.exec() any command does not run in a shell and I bet you use wild cards and/or other commands to be interpreted by a shell which will not be interpreted since there is no shell. And, since you don't mention error messages or the return code, I will also bet you don't process the Process stdout , stderr and the return code properly.
    It looks to me like you have fallen for at least two for the traps in [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html].
    >
    Yet, when I copy the string from the log, and paste it in a terminal, it properly creates the zip files. So, I know I have the correct command string, it just does not seem to be working within the java application. Also, the command string uses fully qualified directories, so it is not a directory issue.
    I am using ubuntu linux.
    Any ideas?I agree with 'masijade' - use the built in Java classes.
    >
    -Adam

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

  • Is there any way to run without using Runtime.getRuntime().exec()

    I am looking for a way to get my program to fun files on my system without using
    Runtime.getRuntime().exec() because it's causing me nothing but problems, is there any other way to do it without using this command?

    Can't think of an easier way (JNI, etc.).
    If you have not read the following article you really should, it might clear up a lot of your problems with exec():
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • How to capture output of java files using Runtime.exec

    Hi guys,
    I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
    import java.io.*;
    public class CmdExec {
      public CmdExec() {
      public static void main(String argv[]){
         try {
         String line;
         Runtime rt = Runtime.getRuntime();
         String[] cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
         Process proc = rt.exec(cmd);
         cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
         proc = rt.exec(cmd);
         //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
    public class E {
        public static void main(String[] args) {
            System.out.println("hello world!!!!");
    }Please help :)

    Javapedia: Classpath
    How Classes are Found
    Setting the class path (Windows)
    Setting the class path (Solaris/Linux)
    Understanding the Java ClassLoader
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • How to copy .gif files from one dir to another using runtime.exec

    hello sir/madem,
    i want to copy some gif and jepg files from one directory to another dir using swing.
    when i tried with using runtime.exec(String[]) i am getting the following error.
    anybody please tell me what is the problem in my program
    java.io.IOException: CreateProcess: ren c:/windows/desktop/copy.java c:/windows/
    cc.java error=0
    code:
    public class copy
         public static void main(String[] args)
              try{
                   String s[]=new String[3];
                        s[0]="ren";
    s[1]="c:/windows/desktop/copy.java";
    s[2]="c:/windows/cc.java";
              Runtime rt=Runtime.getRuntime();
    Process p=rt.exec(s);
              int i=p.waitFor();
              System.out.println("i is "+i);
              }catch(Exception e){System.out.println(e);}
    please mail me to [email protected]
    thanks in advance
    samba reddy
    india

    why use the Runtime? There are methods for this in the IO package ...

  • Problem of executing a process under Linux using Runtime.exec

    Hi, All
    I am having a problem of executing a process under Linux and looking for help.
    I have a simple C program, which just opens a listening port, accept connection request and receive data. What I did is:
    1. I create a script to start this C program
    2. I write a simple java application using Runtime.exec to execute this script
    I can see this C program is started, and it is doing what it supposed to do, opening a listening port, accepting connection request from client and receiving data from client. But if I stop the Java application, then this C program will die when any incoming data or connection request happens. There is nothing wrong with the C program and the script, because if I manually execute this script, everying works fine.
    I am using jre1.4.2_07 and running under Linux fedora 3.0.
    Then I tried similar thing under Windows XP with service pack2, evrything works OK, the C program doesn't die at all.

    Mind reading is not an exact science but I bet that you are not processing either the process stdout or the stderr stream properly. Have you read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html ?

  • Using Runtime.exec to execute Java.exe

    I am trying to use Runtime.exec to spawn a thread that runs java.exe, but havn't had any luck. I have two versions of code, the first one works (example 1), but I want to eliminate the use of "cmd /c" to keep system independance. The second example (example 2) does not work. Both versions work if invoked from the command line. I'm running Win2000. Any Ideas?
    Example 1:
    aProcess = aRuntime.exec("cmd /c java.exe
    -cp "<MyClassPathHere>" <arg1> <arg2> <arg3> <arg4> <arg5>");
    Example 2:
    aProcess = aRuntime.exec("java.exe
    -cp "MyClassPathHere" <arg1> <arg2> <arg3> <arg4> <arg5>");

    I think you mix two concepts: "threads" and "processes". A "thread" is a thread of execution inside the VM, but you want to actually start a new VM in a new process, which is an OS level thing, right?
    I've tried Idea 2 also, same result: works if
    i specify cmd c/, doesn't if I don't.It should work if java.exe is in your path... are you taking care of the standard streams of your process?

  • Is it possible to execute .bat file located in package ?

    Hi,
    in my application i execute a print.bat file using Runtime.exec(), i'd like to place this .bat in package, let's say com.me.testpackage. How is it possible to execute the batch file from that location?
    thanks

    jschell wrote:
    sabre150 wrote:
    jschell wrote:
    >Simple 'for' loops seem to work OK but still more research needed.
    There is escaping in the for loops which is necessary in a bat file and not needed at the command line.
    It seem to be that any command spanning more than one line fails. Fail? The example that gave shouldn't fail. It should simply run both echos.As I understand it, the command sequence
    @echo off
    goto XXX
    echo out
    :XXX
    echo last
    should just output 'last' and not 'out so if it prints both 'out' and 'last' then in my view it 'fails'. Am I missing something?
    >
    >>
    Makes me even more pleased that I work mainly with Linux.Looking up syntax - what about getopts (bourne and korn)? You can also create 'functions', which can be defined later (if I recall correctly) in the script and called multiple times. I don't know how that would work streaming it in.I don't know about consequences of the streaming approach forward definitions in 'bourne' and 'korn' though I was not aware that 'bourne' allowed them. For 'bash' where forward definitions do not seem to be allowed (could I be mistaken in this?) then using        Process process = Runtime.getRuntime().exec("bash", null, new File(System.getProperty("user.home")));the following very simple 'bash' script (which contains loops, if statements and functions but no goto or forward definitions) can be executed without problems - # Simple bash script
    function sayHello {
        echo "Hello" $1
    sayHello "World" ;
    for i in $( ls /tmp ); do
        echo file - $i
    done
    for i in `seq 1 10`;
    do
        echo "seq" $i
    done
    i=0
    while [  $i -lt 6 ]; do
    if [ $i -eq 4 ]; then
        echo "then" $i
    else
        echo "else" $i
    fi
        let i=i+1
    done
    i=12
    until [  $i -lt 10 ]; do
    echo "until" $i
    let i-=1
    doneIn the past, I have also published examples of how to run Perl scripts using the same basic approach. The heart of the examples is         final String perlScript = "#!/bin/perl\n" +
                "print \"PID $$\\n\";\n" +
                "print \"UID $<\\n\";\n" +
                "print \"EUID $>\\n\";\n" +
                "print \"GID $(\\n\";\n" +
                "print \"\\nProcessing the command line arguments\\n\";\n" +
                "foreach (@ARGV) {\n" +
                "    $n = factorial($_);\n" +
                "    print \"    $_! = $n\\n\";\n" +
                "}\n" +
                "print \"\\n\".'@INC'.\"\\n\";\n" +
                "foreach (@INC) {\n" +
                "    print \"    $_\\n\";\n" +
                "}\n" +
                "print \"\\n\".'%ENV'.\"\\n\";\n" +
                "foreach (keys %ENV) {\n" +
                "    print \"    $_==$ENV{$_}\\n\";\n" +
                "}\n" +
                "$x = theAnswerToTheUltimateQuestion();\n" +
                "print \"\\nThe answer to the ultimate question is ... '$x'\\n\";\n" +
                "sub theAnswerToTheUltimateQuestion()\n" +
                "{\n" +
                "    return 3*2*7;\n" +
                "}\n" +
                "sub factorial()\n" +
                "{\n" +
                "    my ($n) = @_;\n" +
                "    return ($n > 1) ? $n * factorial($n-1) : 1;\n" +
                "}\n";
            System.out.println(perlScript);
             * The perl source can be from any InputStream. Here I use a
             * ByteArrayInputStream just as a demonstration.
            final InputStream perlSource = new ByteArrayInputStream(perlScript.getBytes());
             * The '-' indicates that the Perl script comes from stdin. The "a","b","c" etc
             * are the command line arguments passed to the Perl script.
            final String[] command =
                "perl", "-", "5", "6", "7", "8", "9", "10"
            final Process process = Runtime.getRuntime().exec(command);piping the 'perlSource' stream to the process stdin.
    This runs as expected on both Linux (FC9 and Ubuntu 8.04) and on Windows using Active Perl.
    Please don't take my use of a String to hold the Perl script to mean that I in any way endorse this approach - I just wanted a simple means to create a self-contained example.
    >
    And the c shell has a goto also.One day I might find some time and investigate 'c' shell goto in this context - since I have not used csh for at least 8 years I am very rusty.
    I can't say that the 'streaming' approach will work with all Linux shells but I can say that on Linux I have had no problem with Perl and Bash. If anyone needs to use the 'streaming' approach with another shell then it takes just a few minutes to setup a test harness. If any problems are found then people can always resort to the 'Plan B' approach.
    I am still pleased I work mainly with Linux and Unix.

  • Using runtime.exec,process streams

    Hi all,
    I am using runtime.exec to execute a batch file(rmdir /s/q directoryname) which deletes all the files in a certain directory(including subdirectories). However, some of the files are not deleted since they are being used by other processes.
    I have closed all file references but still the batch file says they are being used by other processes. The File.canWrite() method however, returns true for all the files. I have also tried to delete the files using file.delete but it does not work.
    So I have 2 questions.
    1. Can I forcibly delete these files some other way.
    2. If i call a batch file to delete the files and it fails on some files, the command window displays "cannot delete files". How can I write out thse messages into a text file which i can use as a log file.Do I have to use Process.getInputstream()/Process.getInputstream() ? If so, how?
    Thanks for your help.
    Vinny

    I tried the following before but the string i get is always empty, but i can see there are messages in the command window. Please let me now if i am doing something wrong.
    try{
    Process p = rt.exec("cmd.exe /c start deletefiles.bat");
    InputStream ins = p.getInputStream();
    byte[] bytearray = new byte[1024];
    int bytecount;
    String dos_string="";
    BufferedInputStream bis = new BufferedInputStream(ins);
    while ((bytecount = bis.read(bytearray, 0, 1024)) > -1) {
    String str = new String(bytearray,0,bytecount);
    dos_string += str;
    System.out.println("dos string is" +dos_string);
    catch (Exception e) {
    System.out.println("Error: " + e);

  • Parameter  to shell script using Runtime.exec(string)

    Hi all, ( Speciall hi to dheeraj tak )
    Briefly : How do i pass an arguement to a non - java executible being called using Runtime.exec.
    In detail : i am using Runtime.exec to call a shell script : The code is as follows:
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh"};
    try {
    Runtime rt = Runtime.getRuntime();
    Process child = rt.exec(callAndArgs);
    This works properly & calls the shell script which in turn invokes some other executible (c file).
    $HOME/midi/test/build/bin/<C-EXECUTIBLE>
    Here i am specifying the name (say hello.exe ) . So far so good.
    I want to make this happen dynamiclaly. so i need to pass the name of the executible as a parameter to the script.
    To pass a parameter i hav to change the string to :-
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh <C-EXECUTIBLE HERE>"};
    and the script to
    $HOME/midi/test/build/bin/$1 --- where $1 refers to argument 1. (C-EXECUTIBLE AGAIN).
    This is giving an IO - Execption. Plz help
    Code will be very helpful.
    Thanx in advance

    some 1 plz tell me the difference :-
    This is the documentation of Runtime.exec that i found :-
    1> exec
    public Process exec(String command) throws IOException
    Executes the specified string command in a separate process.
    The command argument is parsed into tokens and then executed as a command in a separate process. This method has exactly the same effect as exec(command, null).
    Parameters:
    command - a specified system command
    Complete refernce says : Process (String progName) ----- Executes a program specified by programname as a seperate process.
    2> exec
    public Process exec(String cmdarray[]) throws IOException
    Executes the specified command and arguments in a separate process.
    The command specified by the tokens in cmdarray is executed as a command in a separate process. This has exactly the same effect as exec(cmdarray, null).
    Parameters:
    cmdarray - array containing the command to call and its arguments.
    Complete reference says : Process exec(String comLineArray[]) ---- Executes the command line specified bythe string in comLineArray as a seperate process.
    This means that there is provision 4 command line arguments...
    how do u use it then????????????????????????????

  • Trying to run external script using Runtime.exec

    Hey,
    I am trying to use Runtime.exec(cmd, evnp, dir) to execute a fortran program and get back its output, however it seems to always be hanging. Here is my code snippet :
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName > inputFile.txt" , null, new File("/home/myRunDir/"));
                InputStream stream = new InputStream(process.getInputStream());
                InputStream error = new InputStreamr(process.getErrorStream());
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stream));
                BufferedReader erroutReader = new BufferedReader(new InputStreamReader(error));
                System.out.println(stream.available());  //returns 0
                System.out.println(error.available());     //returns 0
                while (true) {
                    String line1 = stdoutReader.readLine();  //hangs here
                    String line2 = erroutReader.readLine();
                    if (line1 == null) {
                        break;
                    System.out.println(line1);
                    System.out.println(line2);
                }I know for a fact that this fortran code prints out stuff when run it in terminal, but I don't know if I have even set up my Runtime.exec statement properly. I think I am clearing out my error and input streams with the whole reader.readLine bit I have above, but I am not sure. If you replace the command with something like "echo helloWorld" or "pwd", it prints out everything properly. I also am fairly confident that I have no environmental variables that are used in the fortran code, as I received it from another computer and haven't set up any in my bash profile.
    Any Ideas?

    Okay, so I implemented the changes from that website (thanks by the way for that link, it helps me understand this a little better). However, my problem is still occuring. Here is my new code:
                class StreamThread extends Thread {
                InputStream is;
                String type;
                StreamThread(InputStream is, String type)
                    this.is = is;
                    this.type = type;
                public void run()
                    try
                        InputStreamReader isr = new InputStreamReader(is); //never gets called
                        BufferedReader br = new BufferedReader(isr);
                        String line=null;
                        while ( (line = br.readLine()) != null)
                            System.out.println(type  +">"+  line);
                        } catch (IOException ioe)
                            ioe.printStackTrace();
            try {
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName" , null, new File("/home/myRunDir/"));
                StreamThread stream = new StreamThread(process.getInputStream(), "OUTPUT");
                StreamThread errorStream = new StreamThread(process.getInputStream(), "ERROR");
                stream.start();
                errorStream.start();
                int exitVal = process.waitFor(); //hangs here
                System.out.println("ExitValue: " + exitVal);

Maybe you are looking for