How to invoke a CMD file in JAVA correctly on windows?

混江龙づ霸主 提交于 2019-12-11 19:23:19

问题


I have sample java code like below.

    String testEfdDirectoryPath="D:\\test";
    String efdExecutable = "test.cmd";
    File executableFile = new File(testEfdDirectoryPath, efdExecutable);
    ProcessBuilder pb=new ProcessBuilder();
    $$pb.command("cmd.exe","/C",executableFile.toString());$$
    pb.directory(new File(testEfdDirectoryPath));
    Process p=pb.start();
    int code=p.waitFor();
    System.out.print(code);

In test.cmd there is actually a call to another java application. Unless I change the $$ marked line to the following to redirect its output, the another java app cannot be launched.

    pb.command("cmd.exe","/C",executableFile.toString(),">output.txt");

Do you guys have any ideas? Thanks in advance. :)


回答1:


Does your child process produce a lot of output (more than a few kilobytes)? If that is the case, you need to read that output from the process. You should try:

  1. start the process
  2. close the stdin of the process, so pb.getOutputStream().close()
  3. repeatedly read from pb.getInputStream() and the error stream

This may be possible in one thread, or in multiple threads. Anyway, you should just take the explanation above as a list of keywords and try to search for an example code snippet that you can trust, preferrably from an Open Source application that does such a thing successfully.

Maybe http://commons.apache.org/exec/ can help you.




回答2:


Windows cannot execute scripts directly; when you double click on a .cmd file it actually opens the file in cmd.exe. So try cmd.exe E:\\test\\test.cmd.



来源:https://stackoverflow.com/questions/8890414/how-to-invoke-a-cmd-file-in-java-correctly-on-windows

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