简体   繁体   English

通过Java运行批处理文件(.bat)所需的解决方案

[英]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 . 我有一个servlet,试图在其中运行一个批处理文件run.bat

The batch file is for opening a text file like sample.txt placed in a folder like C:/Test/run.bat 批处理文件用于打开放置在C:/Test/run.bat等文件夹中的文本文件(如sample.txt

The program is working fine if I am running this program in Eclipse, ie the text file is opening. 如果我在Eclipse中运行该程序,则该程序运行良好,即文本文件正在打开。 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 . 当我将此应用程序部署到位于位置C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\webapps tomcat wepapps文件夹中时,文本文件也会打开,并使用Tomcat作为服务,即安装了Tomcat,并且通过以下方式访问该应用程序URL localhost:8080/testbatfile/StartTest

testbatfile is project name and StartTest is servlet. testbatfile是项目名称, StartTest是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. 但是,如果我们在Tomcat中部署应用程序并运行Tomcat的startup.bat ,那么一切也都可以正常工作。

Kindly let me know if anybody ready to take this challenge. 请让我知道是否有人愿意接受这一挑战。

The content of the servlet is as follows: servlet的内容如下:

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: run.bat的内容仅是:

"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? 以及为什么您需要一个bat文件来对sample.txt进行处理?

Anyway, you should use exec(String[] cmdarray, String[] envp, File dir) or ProcessBuilder instead of the plain string based exec. 无论如何,您应该使用exec(String [] cmdarray,String [] envp,File dir)ProcessBuilder,而不要使用基于纯字符串的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. 这使您可以指定开始目录,合理的环境,尤其是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. 我怀疑您遇到的问题是Tomcat安装路径中的空白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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