如何在java中运行依赖cmd命令

如何在java中运行依赖cmd命令,java,cmd,Java,Cmd,您好,我需要在java中执行几个互相依赖的cmd命令: cd "C:\Program Files (x86)\puTTY" pscp -pw pwd F:\Test\file_to_send.txt login@my_ip:/home/bin 我试过这样的方法: (一) Runtime.getRuntime().exec(“cmd/c start F:\\Test\\move_to_linux.bat”)并在bat文件中设置: cd "C:\Program Files (x86)\pu

您好,我需要在java中执行几个互相依赖的cmd命令:

cd  "C:\Program Files (x86)\puTTY"
pscp   -pw pwd F:\Test\file_to_send.txt login@my_ip:/home/bin
我试过这样的方法:

(一)

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
(二)

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

是如何运行shell命令的一个很好的示例。运行系统命令不需要打开putty

您可以使用本机java库来执行shell命令,只需注意这些命令是特定于操作系统的。我以前在一个项目中做过这个,我们必须用java模拟一个shell,一旦你知道你在做什么,这很容易

我建议将代码模块化一点。比如说

  • 读取用户输入
  • 解析用户输入
  • 返回错误或执行命令
  • 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();
        }
    }