How to invoke a CMD file in JAVA correctly on wind

2019-09-09 09:13发布

问题:

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.