Using CMD as a Process

后端 未结 6 1655
無奈伤痛
無奈伤痛 2020-12-22 09:38

I\'m trying to run commands straight through the CMD on Windows (Terminal on Linux). I have the following code. It\'s acting very strangely. First, when run the program does

6条回答
  •  無奈伤痛
    2020-12-22 09:59

    You can execute commands without actually hard coding cmd.exe into the code.

    public static void main(String[] args) {
    
          //cmd = the command youw ill be using            
        String cmd = "ipconfig";      
        Runtime r = Runtime.getRuntime();      
        Process p;   
        try {       
            p = r.exec(cmd);
    
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));    
        String inputLine;       
        while ((inputLine = in.readLine()) != null) {     
            System.out.println(inputLine);
              }       
        }     
    
    
    catch (IOException ex) {      
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);  
                 }
           }
    

提交回复
热议问题