简体   繁体   中英

Solution needed to run batch file (.bat) through java

I have one servlet in which I am trying to run one batch file - run.bat .

The batch file is for opening a text file like sample.txt placed in a folder like C:/Test/run.bat

The program is working fine if I am running this program in Eclipse, ie the text file is opening. And the text file opens also when I deployed this application in tomcat wepapps folder at location C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\webapps , use Tomcat as a service, ie Tomcat is installed, and I am accessing the application through the URL localhost:8080/testbatfile/StartTest .

testbatfile is project name and StartTest is servlet.

But if I am trying to run the application through browser, it is not working. The program is not able to run the batch file.

But everything is also working fine if we deploy the application in Tomcat and run startup.bat of Tomcat.

Kindly let me know if anybody ready to take this challenge.

The content of the servlet is as follows:

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws   ServletException, IOException {
    Runtime runtime = Runtime.getRuntime();
    Process p1 = runtime.exec("C:/CGT_TO_SAS/run.bat");

    InputStream is = p1.getInputStream();
    int i = 0;

    while( (i = is.read() ) != -1)
    {
        System.out.print((char)i);
    }
}

The content of run.bat is just:

"C:\Test\sample.txt"

Your batch file content looks broken, this is not a valid command. And why would you need a bat file to do what with a sample.txt?

Anyway, you should use exec(String[] cmdarray, String[] envp, File dir) or ProcessBuilder instead of the plain string based exec. This allows you to specify the start directory, a sane environment and especially a command name and arguments which are not interpreted by your OS.

runtime.exec(new String[]{"C:/CGT_TO_SAS/run.bat"}, null, new File("C:/CGT_TO_SAS"));

I suspect the problem in your case is the blank in the path of the Tomcat installation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM