tags:

views:

179

answers:

3

I have a batch file runthis.bat

dir >dir.txt

If I double click on this, a text file is being created with name dir.txt

Now I have to run this batch file using JSP.

<%
Runtime run =Runtime.getRuntime();
run.exec("C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/try/runthis.bat");
out.println("SUCCESS");
%>

I'm getting the output SUCCESS on a webpage but this batch file is not running.

Whats might be the problem?

+1  A: 

I guess you should use backspaces in the path:

run.exec("C:\\Program Files\\Apache Software Foundation\\Tomcat 5.5\\webapps\\try\\runthis.bat");
Péter Török
+2  A: 

Try executing:

cmd /c your.bat

That is:

run.exec("cmd /c C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/try/runthis.bat");

EDIT:

And I would suggest you to be careful with spaces within the path. It would be great if you escaped them or wrapped the whole path with quotes ("").

Grzegorz Oledzki
If you're worried about spaces in the path, it might be safer to use Runtime.exec(String[]) instead of Runtime.exec(String).
Alison
+2  A: 

First, JSP is the wrong place for this. Do it in a real Java class. Start with a Servlet. Have a form with a button which submits to a servlet. Put this code in the doPost() method. Let the servlet put the result in request scope and forward the request to a JSP. Let the JSP display the result.

Second, learn the pitfalls of Runtime#exec() in this article. Your problem is that you aren't checking the result nor the error stream (and thus never knows if the program executed successfully) and that you are expecting that it somehow runs in sync with your coding (while it actually runs in a separate thread/process). You're basically doing a "fire and forget", the code is basically not tracking the execution/termination of the program in any way.

This problem has by the way nothing to do with JSP. You would face exactly the same problem when doing so in a normal Java class.

BalusC