How to execute cmd commands via Java

前端 未结 11 2171
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 13:59

I am trying to execute command line arguments via Java. For example:

// Execute command
String command = \"cmd /c start cmd.exe\";
Process child = Runtime.ge         


        
11条回答
  •  一生所求
    2020-11-22 14:54

    The code you posted starts three different processes each with it's own command. To open a command prompt and then run a command try the following (never tried it myself):

    try {
        // Execute command
        String command = "cmd /c start cmd.exe";
        Process child = Runtime.getRuntime().exec(command);
    
        // Get output stream to write from it
        OutputStream out = child.getOutputStream();
    
        out.write("cd C:/ /r/n".getBytes());
        out.flush();
        out.write("dir /r/n".getBytes());
        out.close();
    } catch (IOException e) {
    }
    

提交回复
热议问题