Executing cmd file contained in a folder with spac

2019-09-01 08:47发布

I am trying to run the cmd file using JDK7u25 with following code:

try {
            ProcessBuilder pb = new ProcessBuilder(cmd);
            pb.directory(workingDir);
            proc = pb.start();
        } catch (IOException e) {
            System.out.println(e.getMessage());
            throw e;
        }
        // StdOut and Err Stream must be read immediatly even if they are not used

        // any error message?
        StreamInlet error = new StreamInlet(proc.getErrorStream(), "ERROR");

        // any output?
        StreamInlet output = new StreamInlet(proc.getInputStream(), "OUTPUT");

        // kick them off
        error.start();
        output.start();

        if (wait) {
            try {
                exitCode = proc.waitFor();
            } catch (InterruptedException e) {
                System.out.println("Waiting for process was interrupted");
            }
            if (addMetaInfo)
                System.out.println("Return value = " + exitCode);
        }

where cmd=[cmd.exe, /c, C:\My Root\scripts\windows\tools\MyCLI.cmd, -c, C:\Local Disk D\My Tutorial\RegressionTests.xml, -d, 02_RecordViewer_Test, -l"ERROR"]

But it doesn't work and I get following output.

'C:\My' is not recognized as an internal or external command,

operable program or batch file.

I have already made the necessary changes for JDK7U21 issue by adding explicit "CMD.EXE /C" before calling the cmd file. Also I am using the ProcessBuilder class too as mentioned in the JDK7u21 issue.

It works fine if the cmd file I am trying to execute is placed in C:\MyRoot i.e. a folder without space in it's name.

Can someone please help?

标签: java cmd
3条回答
做个烂人
2楼-- · 2019-09-01 08:50

I just noticed that this issue has already been addressed in JDK7u25. I just found it in it's Release Notes.

查看更多
孤傲高冷的网名
3楼-- · 2019-09-01 08:51

I'd be tempted to change the backslashes to forwards slashes, and escape the spaces.

C:/My\ Root/scripts/windows/tools/MyCLI.cmd
查看更多
地球回转人心会变
4楼-- · 2019-09-01 09:00

You need to enclose your paths in quotation marks as cmd requires:

String[] cmd = {"cmd.exe", "/c", "\"C:\\My Root\\scripts\\windows\\tools\\MyCLI.cmd\"", "-c", "\"C:\\Local Disk D\\My Tutorial\\RegressionTests.xml\"",.....};

Update as we discussed via chat, the problem seems to be ProcessBuilder passing parameters to cmd.exe. But as you have the complete path to your executable, actually cmd.exe is no needed at all. So the command would look like this:

String[] cmd = {"\"C:\\My Root\\scripts\\windows\\tools\\MyCLI.cmd\"", "-c", "\"C:\\Local Disk D\\My Tutorial\\RegressionTests.xml\"",.....};
查看更多
登录 后发表回答