Runtime.getRuntime().exec() in JSP - Starting a batch

Hi,
I am trying to start a batch from a jsp in the following way:
try{
String path = "bat/drucken";
ProcessBuilder processBuilder = new ProcessBuilder(path);
Process process = processBuilder.start();
out.println("<script type=\"text/javascript\">alert('ausgeführt.');</script>");
}catch(Throwable t){
t.printStackTrace();
out.println("<script type=\"text/javascript\"> alert('Fehler beim Drucken.');</script>");
But onfortunately it does not work the way I want.
If I double click the batch file, it works properly and starts a visual basic script, that makes out of n word-documents one single one.
If I start it like above, then nothing happens and just the alert('ausgeführt') appears.
How can I start a VB script or a commands of the shell from inside a jsp ?
PS: using Windows XP, jsp should work on a Windows Server

As Liane said, this should NOT be in your JSP. This should be in a normal Java file, compiled to a class, in a package, and deployed in the Web Application's /WEB-INF/classes/ directory.
Example. Change the code to this:
//Put your class in a package
package debbie.in.florida;
import java.io.*;
public class Console{
    String error = null;
    String output = null;
    public String getError(){
        return error;
    public String getOutput(){
        return output;
    /** Called from inside the jsp like new Console().exec("cscript drucken.vbs param1 param2") **/
    public void exec(){
        try{
            String osName = System.getProperty("os.name" );
            String[] cmd = new String[3];
            cmd[0] = "cmd.exe" ;
            cmd[1] = "/C" ;
            cmd[2] = "Test.exe";
            Runtime rt = Runtime.getRuntime();
            System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
            Process proc = rt.exec(cmd);
            // any error message?
            grabStream(proc.getErrorStream(), "error");
            // any output?
            grabStream(proc.getInputStream(), "output");
            // any error???
            int exitVal = proc.waitFor();
            if (exitVal != 0)
                error += "ExitValue: "+exitVal;
        } catch (Exception e){
            e.printStackTrace();
    private void grabStream(InputStream is, String msg){
        if (!(msg.equals("error") || msg.equals("output")))
            return;
        String message = "";
        try{
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
                message += line;
        } catch (IOException ioe){
            ioe.printStackTrace();
        if (msg.equals("error"))
            error = message;
        else
            output = message;
}Then compile the code and move the Console.class file to <web application>/WEB-INF/class/debbie/in/florida/Console.class. The folder should be debbie/in/florida because the package is defined as debbie.in.florida.
Then your JSP would look like:
    <%//Use the debbie.in.florida namespace because your class is in a package
        debbie.in.florida.Console console = new debbie.in.florida.Console();
    %>
    <script type="text/javascript">
        alert("start");
    </script>
    <%
        console.exec();
        String error = console.getError();
        String output = console.getOutput();
    %>
    <script type="text/javascript">
        alert("end, output = <%=output%> and error = <%=error%>");
    </script>There is a lot wrong with this code, but I won't go and try to fix design problems here, That will be for a later day. But if things are working you should get two popups, one at the start, then your code should execute (or you should get an error message if something is wrong with the code), then a second popup at the end with the response from your application.

Similar Messages

  • Runtime.getRuntime().exec("cmd /c start file\\"+"My file.txt" ) Not work

    Hello
    i have a problem I use:
    Runtime.getRuntime().exec("cmd /c start file\\"+"My file.txt");
    to open "my file.txt" And I have error System Windows don't open file file\My becaus file My don't exist When I rename file to "Myfile.txt" and use:
    Runtime.getRuntime().exec("cmd /c start file\\"+"Myfile.txt");
    It's work great. My problem is when my file have space in name or other [ ], etc symbol. How fix this problem?
    Thenks to help:)

    Try using the verson where you specify the parameters in an array as this example shows:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=635363
    Note: you may need to enclose the file name in quotes

  • How to use Runtime.getRuntime().exec() in JSP? is it works in JSP or not

    Hi to all,
    i want run a .exe file from JSP file. In java i am able do this, using Runtime.getRuntime().exec().
    but same thing, when i trying with JSP it is not working?
    plz let me is there any other ways to do it..

    It depends, usually (ie in an J2EE container) you're not allowed to access files or the runtime environment, by definition. What do you wan't to achieve with the exe?
    --olaf                                                                                                                                                                                                                                                                                                                                                           

  • Weird behaviour with Runtime.getRuntime.exec() attempting to start IE

    I have developed a sample scheduler that it a web page the user fill in and then create a process schedule by the Timer class. The process starts IE in order to automate data entry normally done by a user. The Java code run well but IE when start from the p = Runtime.getRuntime().exec() class freeze. Is anyone can tell if IE require special setting to run in background?
    Here the Java code but once again it work well but IE freeze and cause the forked process to hang.
    // The schedule task
    public void scheduleTask(Object o) throws ApplicationException {
    ScheduleBean sb = (ScheduleBean)o;
    try {
    Timer timer = new Timer(true);
    RunReslotting rr = new RunReslotting();
    timer.schedule(rr, sb.getSchedulingDate());
    catch(IllegalArgumentException iae) {
    throw new ApplicationException(iae.getMessage());
    catch(IllegalStateException ise) {
    throw new ApplicationException(ise.getMessage());
    public class RunReslotting extends TimerTask {
    protected RunReslotting() {
    public void run() {
    String[] cmdLineParam = transportProfile(2);
    cmdLineParam[0] = "location=" + wr.getLocation();
    cmdLineParam[1] = "loc_class=" + wr.getNewStrategy();
    forkProcess("runie.bat", cmdLineParam);
    private String[] transportProfile(int startAt) {
    envProf = System.getenv();
    profCmd = new String[envProf.size() + startAt];
    itr = envProf.entrySet().iterator();
    int i = startAt;
    while (itr.hasNext()) {
    entry = (Map.Entry)itr.next();
    profCmd[i] = (String)entry.getKey() + "=" + (String)entry.getValue();
    i++;
    return profCmd;
    private void forkProcess(String processName, String[] osParam) throws ApplicationException {
    // Lance un nouveau process
    p = null;
    int i=0;
    try {
    p = Runtime.getRuntime().exec(processName, osParam);
    // Vide les buffers du process pour eviter de geler
    mcError = new MessageCatcher(p.getErrorStream());
    mcOutput = new MessageCatcher(p.getInputStream());
    mcError.start();
    mcOutput.start();
    i = p.waitFor();
    if ( (i != 0) || (mcError.getMessage() != null) || (mcOutput.getMessage() != null) ) {
    System.err.println("*** Process failed RC:" + i + " *** ");
    if (mcOutput.getMessage() != null) {
    System.err.println("Output messages: " + mcOutput.getMessage());
    if (mcError.getMessage() != null) {
    System.err.println("Error messages: " + mcError.getMessage());
    throw new ApplicationException("*** Process failed *** ");
    catch(IOException ioe) {
    throw new ApplicationException(ioe.getMessage());
    catch(InterruptedException ie) {
    throw new ApplicationException(ie.getMessage());
    Any suggestion will be appreciate. I�m working on that scheduler for a while and i'm desperate
    Thanks
    Francis

    This starts IE for me, no problem
    String[] cmd = {"C:\\Program Files\\Internet Explorer\\iexplore.exe"};
    Runtime.getRuntime().exec(cmd);

  • Problem in Runtime.getRuntime().exec

    Hi,
    I am trying to start the tomcat server through a java application.Before starting the server,i need to run a batch file for setting up some classpaths.I am able to run the batch file and start the server,but its opening the 2 windows.How do i suppress it?
    One more problem is how do i stop the server?
    Code is:
    import java.io.*;
    public class Test
    public static void main(String args[]) {
    try {
         Process p = Runtime.getRuntime().exec("cmd /c start C:\\soap.bat");     
         p.destroy();
         Process p1 = Runtime.getRuntime().exec("cmd /c start C:\\jakarta-tomcat-3.2.1\\bin\\startup");
         //p.waitFor();     
         Thread.sleep(10000);
         p1.destroy();     
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    bw.write("1");
    bw.flush();
    String line;
    while ((line = br.readLine()) != null) {
    System.out.println(line);
    br.close();
    bw.close();
    System.out.println(p.exitValue());
    catch(Exception e) {
    System.out.println(e);
    I need the help as early as possible.
    pls cc reply to:[email protected]
    Thanks
    Anitha

    Soln. to your first prob:
    1) To have the other DOS window closed, click on the extreme left-top corner of that window. In the menu that drops down ,select properties.In the properties window make sure the 'close on Exit' check Box is checked. Apply the changes.
    2) To stop the server u need to call the shutdown.bat file in the tomcat\bin dir. If u want to do this thru java then call the shutdown.bat file from your Runtime.exec() method. Same as u did for the startup file
    Hope this helps.

  • Runtime.getRuntime().exec problems

    i am trying to run files from my java application, i use the following command
    Runtime.getRuntime().exec("cmd /c start " + filePath);but it seems that it cant handle file path with spaces, like
    C:\Documents and Settings\Administrator\My Documents\My Web\Untitled-3.fla
    it works well with path like this
    C:\Downloads\1.rar
    am i right? and how to solve this problem? thanks

            final String[] command =
                "cmd.exe",
                "/C",
                "start \"" + filename + "\"",
            final Process p = Runtime.getRuntime().exec(command);this method can only trigger files in the same folder as the java application, isnt it?

  • Access denied when Runtime.getRuntime().exec

    I have an applet that opens a JFrame.
    In the JFrame I have a JButton, when I click the button I want a browser to open with a specific website.
    This doesn't work.
    When I look in the cmd-prompt it says:
    "java.security.AccessControlException: access denied (java.io.FilePermission C:\Program execute)"
    What have I done wrong? Do I have to change the security settings? Where do I that?
    class KnappListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    frame2 = new JFrame(e.getActionCommand());
    frame2.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    String website = new String("http://www.microsoft.com");
    try {
    Runtime.getRuntime().exec("C:\\Program Files\\Internet Explorer\\IEXPLORE.exe"+website);
    //Runtime.getRuntime().exec("cmd/C"+"start.exe"+website);
    catch (IOException io) {}
    }

    it doesn't matter which class your program extends. if your program is an applet (running in a browser) it is not permitted to use Runtime.getRuntime().exec(). If your program is an application, it is allowed to do so.
    I think there is a way for applets to get the permission through a policy, but I don't know how to do this.

  • Executing Batch files from Runtime.getRuntime().exec

    Can we execute batch files from Runtime.getRuntime().exec() method.
    Regards,
    Nalini

    hi,
    import java.io.IOException;
    class BatchFileTest{
         public static void main(String args[]){
              try{
              Runtime r = Runtime.getRuntime();
              Process p = r.exec("startcmd.bat");
              catch(IOException en){
                   en.printStackTrace();
    -Regards
    Manikantan

  • Problems with Runtime.getRuntime().exec in Windows 2000

    Hello,
    I have a batch file that I want to run from my java application. My code is the following:
    try {
            Runtime.getRuntime().exec("cmd.exe /c C:\\temp\\shortcut.bat");
    } catch (Exception e) {
         System.out.println(e.getMessage());
    }I was developing on windows XP and it worked just fine. But then I tested it on windows 2000 and it didn't work. The batch file is okay, because if I run the batch file myself it works just fine, even from the command line. I get no errors what so ever, it just doesn't do anything...
    Can somebody help me with this?
    thx in advance

    thank you all so much
    I figured it out... It was a combination of two things that went wrong.
    First one: in my batch file I had:
    cd C:\tempwhich worsk fine in XP, but in it doesn't in 2000. In 2000 it has to be:
    C:
    cd \temp But just changing that wasn't enough, I also needed the "start"
    Now it works just fine on 2000, hopefully it'll still work on xp as well.
    THX!

  • Strange behaviour of Runtime.getRuntime().exec(command)

    hello guys,
    i wrote a program which executes some commands in commandline (actually tried multiple stuff.)
    what did i try?
    open "cmd.exe" manually (administrator)
    type "echo %PROCESSOR_ARCHITECTURE%" and hit enter, which returns me
    "AMD64"
    type "java -version" and hit enter, which returns me:
    "java version "1.6.0_10-beta"
    Java(TM) SE Runtime Environment (build 1.6.0_10-beta-b25)
    Java HotSpot(TM) 64-Bit Server VM (build 11.0-b12, mixed mode)"
    type "reg query "HKLM\SOFTWARE\7-zip"" returns me:
    HKEY_LOCAL_MACHINE\SOFTWARE\7-zip
    Path REG_SZ C:\Program Files\7-Zip\
    i wrote two functions to execute an command
    1) simply calls exec and reads errin and stdout from the process started:
    public static String execute(String command) {
              String result = "";
              try {
                   // Execute a command
                   Process child = Runtime.getRuntime().exec(command);
                   // Read from an input stream
                   InputStream in = child.getInputStream();
                   int c;
                   while ((c = in.read()) != -1) {
                        result += ((char) c);
                   in.close();
                   in = child.getErrorStream();
                   while ((c = in.read()) != -1) {
                        result += ((char) c);
                   in.close();
              } catch (IOException e) {
              return result;
         }the second function allows me to send multiple commands to the cmd
    public static String exec(String[] commands) {
              String line;
              String result = "";
              OutputStream stdin = null;
              InputStream stderr = null;
              InputStream stdout = null;
              // launch EXE and grab stdin/stdout and stderr
              try {
                   Process process;
                   process = Runtime.getRuntime().exec("cmd.exe");
                   stdin = process.getOutputStream();
                   stderr = process.getErrorStream();
                   stdout = process.getInputStream();
                   // "write" the parms into stdin
                   for (int i = 0; i < commands.length; i++) {
                        line = commands[i] + "\n";
                        stdin.write(line.getBytes());
                        stdin.flush();
                   stdin.close();
                   // clean up if any output in stdout
                   BufferedReader brCleanUp = new BufferedReader(
                             new InputStreamReader(stdout));
                   while ((line = brCleanUp.readLine()) != null) {
                        result += line + "\n";
                   brCleanUp.close();
                   // clean up if any output in stderr
                   brCleanUp = new BufferedReader(new InputStreamReader(stderr));
                   while ((line = brCleanUp.readLine()) != null) {
                        result += "ERR: " + line + "\n";
                   brCleanUp.close();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              return result;
         }so i try to execute the commands from above (yes, i am using \\ and \" in java)
    (1) "echo %PROCESSOR_ARCHITECTURE%"
    (2) "java -version"
    (3) "reg query "HKLM\SOFTWARE\7-zip""
    the first function returns me (note that ALL results are different from the stuff above!):
    (1) "" <-- empty ?!
    (2) java version "1.6.0_11"
    Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing)
    (3) ERROR: The system was unable to find the specified registry key or value.
    the second function returns me:
    (1) x86 <-- huh? i have AMD64
    (2) java version "1.6.0_11"
    Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing)
    (3) ERROR: The system was unable to find the specified registry key or value.
    horray! in this version the java version is correct! processor architecture is not empty but totally incorrect and the reg query is still err.
    any help is wellcome
    note: i only put stuff here, which returns me strange behaviour, most things are working correct with my functions (using the Runtime.getRuntime().exec(command); code)
    note2: "reg query "HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0" /t REG_SZ" IS working, so why are "some" queries result in ERR, while they are working if typed by hand in cmd.exe?

    ok, i exported a jar file and execute it from cmd:
    java -jar myjar.jar
    now the output is:
    (1) "" if called by version 1, possible to retrieve by version 2 (no clue why!)
    (2) "java version "1.6.0_10-beta"
    Java(TM) SE Runtime Environment (build 1.6.0_10-beta-b25)
    Java HotSpot(TM) 64-Bit Server VM (build 11.0-b12, mixed mode)"
    (3) C:\Program Files\7-Zip\
    so all three problems are gone! (but its a hard way, as i need both functions and parse a lot of text... :/ )
    thanks for the tip, that eclipse changes variables (i really did not knew this one...)

  • Runtime.getRuntime.exec() not working when Tomcat is made a windows Sevice

    Hi,
    I am working on a web application which launches a exe file on subitting the form. I am using Apache Tomcat 4.0.6 to run the web application. Initially Tomcat was not made a windows service on my machine and when I launch an exe it is launching without any problems. I used the following command to launch the exe file:
    <code>
    Process p = Runtime.getRuntime().exec("C:\\Program Files\\Mercury Interactive\\WinRunner\\arch\\wrun.exe" + strWROptions);
    </code>
    The above command launches WinRunner on the local machine.
    without using tomcat if I just compile and run a test program with this command, the exe is launching perfectly. But, Once I made tomcat a windows service on my machine the exe is not launching.
    Also, a process is being created in the windows task bar named wrun.exe once I submit the form but WinRunner is not lauching on the desktop.
    Can any one please help and suggest me.
    Thanks,
    Ramesh

    The version of Java I am using is 1.4.2. Even without
    using the string array as you mentioned, the exe
    (wrun.exe) is launched on my desktop if I don't run
    Tomcat as a windows service. But the problem arises on
    making it a service :-(
    That is strange because going by the documentation what you have been using should never work. I can't test it though, I'm not on MSWindows at the moment..
    Now, when I use this string array convention, I am
    getting an error saying "The tool could not launch..
    some error occured".
    That's not a Java error message, it must come from WinRunner. This means that you have succesfully started WinRunner (great!) but something else is wrong; maybe the parameters you pass to it are incorrect.
    How would you run it on the command line? Like this?wrun -t "D:\L5_QE\L5A\Initial" -create_text_report on -runThat line executes the wrun program and passes it five parameters, not three. The first parameter is "-t", the second "D:\L5_QE\L5A\Initial", the third "-create_text_report", the fourth "on", and the fifth "-run". The array of strings that corresponds to that line isString[] command = {"C:\\Program Files\\Mercury Interactive\\WinRunner\\arch\\wrun.exe",
                    "-t", "D:\\L5_QE\\L5A\\Initial",
                    "-create_text_report", "on",
                    "-run"};

  • Process via Runtime.getRuntime().exec(), how to identify that it�s closed?

    A process(console program) is started via Runtime.getRuntime().exec() from Swing Application.
    Swing Application need to know the result of this process.
    So, is there any possibility to find whether the console program is finished?

    Runtime.exec() returns a Process object.
    Look at its methods, especially waitFor(). Read carefully the whole Process documentation, especially what has to be done with the output streams.

  • Using Runtime.getRuntime().exec(DOS Program) with Windows 2000.

    I am trying to spawn a DOS Program from within Java.
    On Win95/98/ME, I use
    Process     p = Runtime.getRuntime().exec("START /w command.com con /c myDOSProgram.exe");
    This works on these platforms. On Win 2000, I use
    Process     p = Runtime.getRuntime().exec("START /w cmd.exe con /c myDOSProgram.exe");
    It does not work at all.
    I have tried all combinations of using START, cmd.exe, con /c, etc.
    I can spawn a Windows App using
    Process     p = Runtime.getRuntime().exec("windows.exe");
    And it works fine.
    What does it take to spawn a DOS program from Java on the Windows 2000 op sys?

    Hi. I recently wrote a java GUI that calls a DOS program with mixed success. Here's the code I used to make the call:String osName = System.getProperty("os.name" );
    String[] cmd = new String[4];
    if( osName.equals( "Windows 2000" ) || osName.equals( "Windows NT" ) )
         cmd[0] = "cmd.exe";
         cmd[1] = "/C" ;
         cmd[2] = "VBDoc.exe";
         cmd[3] = fileName;
    else if( osName.equals( "Windows 95" ) || osName.equals( "Windows 98" ) )
         cmd[0] = "command.com" ;
         cmd[1] = "/C" ;
         cmd[2] = "VBDoc.exe";
         cmd[3] = fileName;
    else
         System.out.println(osName);
    Process proc = runtime.exec(cmd);Check out this article, it gives a good explanation of how to use the exec() call:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Hope this helps!

  • Runtime.getRuntime().exec() error message "cannot execute"

    I'm trying to start another program written in c++ with the commands:
    p=Runtime.getRuntime().exec("nameofmyprogram");
    it works with other programs written in java, and also with ordinary unixcommands like "ls" etc. but when I try to start the c++-one I get the message: cannot execute.
    I can start the program directly from the terminal window, so it's ok.
    does anybody have any idea of what I'm doing wrong?
    ( my friend claims that it has to have a name ending with .exe, is that true?)
    grateful for advice!

    My first guess would be that the program is not on the path and Java cannot find the executable, ls on the other hand is on the path..
    I'm assuming that you are running on a unix system as you are using ls, so in this case your program does not need to end in exe, this is a windows thing. If your C++ program compiled on windows it would end in exe, but this is not the case on unix systems.
    I would suggest you try either giving the exec method ./nameofmyprogram assuming java is working in the directory your compiled c++ program. The other is to give the exact location.

  • Opening a new browser using Runtime.getRuntime().exec(cmd); under windows

    Can Runtime.getRuntime().exec(cmd); open a URL in to a new browser in wondows OS or ...can we force it to any specific browser insted on OS's default browser...
    It does open a new bowser under MAC but not under windows..
    cmd = "'rundll32 url.dll,FileProtocolHandler"+URL (windows)
    Thanks

    public class WindowsProcess
         public static void main(String[] args)
              throws Exception
              String[] cmd = new String[3];
              cmd[0] = "cmd.exe";
              cmd[1] = "/C";
              cmd[2] = "start";
              Process process = Runtime.getRuntime().exec( cmd );
              process = Runtime.getRuntime().exec( cmd );
    }When you run the above code you should get two open dos windows.
    Now just just enter some html filename and hit enter in each window. IE should start up separately in each window.
    Thats also what should happen if you specify the html file as the fourth parameter. A new process should be created and two separate windows should open with a browser in each.

Maybe you are looking for