Java: Running cmd commands (multiple commands with multiple arguments at once)

扶醉桌前 提交于 2019-12-23 05:26:07

问题


I run cmd (command line) and running my batch file from Java this way:

final String cmd = "cmd /c C: && dir && cd C:\MyApp\Maxi && dir && C:\MayApp\Maxi\deploy.bat";

try {


            Process process = Runtime.getRuntime().exec(cmd);

            final InputStream in = process.getInputStream();

            int ch;

            while((ch = in.read()) != -1) {
                System.out.print((char)ch);
            }
        } catch (IOException e) {
             System.out.println("IOException on CMD executing statement");
             e.printStackTrace();
        }

It was working successfully, but I modified the batch file and added some argument, so I have to pass a name to the batch file so i tried this: (I send "Name1" as argument)

final String cmd = "cmd /c C: && dir && cd C:\MyApp\Maxi && dir && C:\MayApp\Maxi\deploy.bat Name1";

try {


            Process process = Runtime.getRuntime().exec(cmd);

            final InputStream in = process.getInputStream();

            int ch;

            while((ch = in.read()) != -1) {
                System.out.print((char)ch);
            }
        } catch (IOException e) {
             System.out.println("IOException on CMD executing statement");
             e.printStackTrace();
        }

But its not working now and the command is not executed. I only get the "dir" command output.

Can anyone help ?

Note: The commands run successfully on CMD, but its not working from java.


回答1:


Why do you want do multiple tasks in one command? e.g. Change to C:\, dir and then execute?

You can easily club all these tasks to one batch file.

That would help you "not" compiling you code again in case some directory structure changes.



来源:https://stackoverflow.com/questions/17072849/java-running-cmd-commands-multiple-commands-with-multiple-arguments-at-once

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