how to run a batch file from java?

我怕爱的太早我们不能终老 提交于 2020-01-15 11:43:13

问题


I am trying run a batch file from my java codes, but unfortunately I could not run it properly. Actually the batch file is running but only the first line of the batch file is running, so please give solution to it, here are the codes and the batch file.

 class bata
{
public static void main(String [] args)
{
try
{
 Runtime.getRuntime().exec("start_james.bat");


  }
  catch(Exception e) {}
}
}

and the batch file is

cd\
c:
cd C:\Tomcat 5.5\webapps\mail_testing\james-2.3.2\bin
run.bat

start

回答1:


What do you expect cd: to do? That doesn't look right to me...

If your batch file is only going to run another batch file, why not run that target batch file to start with? If you're worried about the initial working directory, use the overload which takes a File argument to say which directory to use. For example:

File dir = new File("C:\\Tomcat 5.5\\webapps\\mail_testing\\james-2.3.2\\bin");
Runtime.getRuntime().exec("start_james.bat", null, dir);



回答2:


If all the other answers (with valid batch file) didn't work try executing cmd.exe directly like this:

File dir = new File("D:\\tools\\bin");
Runtime.getRuntime().exec("c:\\windows\\system32\\cmd.exe /c start_james.bat", null, dir);

You might also use the %SystemRoot% environment variable to get the absolute path to cmd.exe.




回答3:


Isn't there something in java, whereby you can invoke the batch file directly with full path?

I mean, why do you need to change directories?
Also, what is the use of cd:? It is not a valid command in DOS, unless you are using *nix.




回答4:


I think he wants to change to a directory and then run the batch file. Can you try this ?

cd /d C:\Tomcat 5.5\webapps\mail_testing\james-2.3.2\bin
run.bat

start



回答5:


Was "cd:" supposed to be a label you can jump to using the GOTO command? However labels are declared using ":labelname". This should be the reason why your batch execution stops after the first line.




回答6:


This works like a charm:

 Runtime run = Runtime.getRuntime();
    try
    {
    System.out.println("Start Running the batch file");
    Process p = run.exec(new String[]{"cmd.exe","/c", "start", "C:/Users/sony/Documents/NetBeansProjects/CodeReview/src/codereview/install.bat",i,j,m,l});
    System.out.println("Completed");
    }
    catch (Exception e)
    {
    } 

here i,j,k,l are parameter passing to batch file



来源:https://stackoverflow.com/questions/1485781/how-to-run-a-batch-file-from-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!