繁体   English   中英

如何在Java中运行相关的cmd命令

[英]how run dependent cmd commands in java

嗨,我需要在Java中执行几个相互依赖的cmd命令:

cd  "C:\Program Files (x86)\puTTY"
pscp   -pw pwd F:\Test\file_to_send.txt login@my_ip:/home/bin

我尝试过这样的方法:

1)

Runtime.getRuntime().exec("cmd /c start F:\\\\Test\\\\move_to_linux.bat"); 并在bat文件中设置:

cd  "C:\Program Files (x86)\puTTY"
pscp   -pw pwd F:\Test\file_to_send.txt login@my_ip:/home/bin

2)

try {
        String[] command = new String[3];
        command[0] = "cmd";
        command[1] = "/c";
        command[2] = "cd \"C:\\Program Files (x86)\\puTTY\" && pscp   -pw pwd F:\\Test\\file_to_send.txt login@my_ip:/home/bin";

        Process p = Runtime.getRuntime().exec(command);

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String Error;
        while ((Error = stdError.readLine()) != null) {
            System.out.println(Error);
        }
        while ((Error = stdInput.readLine()) != null) {
            System.out.println(Error);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

在1)中,cmd在F:\\ Test文件夹中打开,并且命令分别从F:\\ Test运行。 2)'pscp'不被识别为内部或外部命令,

是如何运行shell命令的一个很好的例子。 您无需打开腻子即可运行系统命令。

您可以使用本机Java库执行Shell命令,只是要注意这些命令是特定于OS的。 我之前在一个必须在Java中模拟shell的项目中完成了此操作,一旦您知道自己在做什么,就很容易。

我建议对您的代码进行一些模块化。 例如

  1. 读取用户输入
  2. 解析用户输入
  3. 返回错误或执行命令

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM