Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Windows commands in JAVA and return the result text as a string [duplicate]

Tags:

java

windows

Possible Duplicate:
Get output from a process
Executing DOS commands from Java

I am trying to run a cmd command from within a JAVA console program e.g.:

ver

and then return the output of the command into a string in JAVA e.g. output:

string result = "Windows NT 5.1"
like image 528
Mike Avatar asked Jan 22 '12 18:01

Mike


2 Answers

You can use the following code for this

import java.io.*; 

    public class doscmd 
    { 
        public static void main(String args[]) 
        { 
            try 
            { 
                Process p=Runtime.getRuntime().exec("cmd /c dir"); 
                p.waitFor(); 
                BufferedReader reader=new BufferedReader(
                    new InputStreamReader(p.getInputStream())
                ); 
                String line; 
                while((line = reader.readLine()) != null) 
                { 
                    System.out.println(line);
                } 

            }
            catch(IOException e1) {e1.printStackTrace();} 
            catch(InterruptedException e2) {e2.printStackTrace();} 

            System.out.println("Done"); 
        } 
    }
like image 153
Kamran Ali Avatar answered Sep 28 '22 06:09

Kamran Ali


You can use Runtime exec in java to execute dos commands from java code.

Process p = Runtime.getRuntime().exec("cmd /C ver");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()),8*1024);

BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

// read the output from the command

String s = null;
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) 
System.out.println(s.replace("[","").replace("]",""));

Output = Microsoft Windows Version 6.1.7600

like image 26
RanRag Avatar answered Sep 28 '22 05:09

RanRag