Monday, March 9, 2009

Reading Command Promt Output from JAVA


Hello Friends,


If sometimes you need reading a cmd.exe's output in java.
Here i am putting the code for doing that.

It is based on Buffered Readers's readLine() method.

But the point of attention is how to get your exe's InputStream.

See the snapshot in example i am reading a drive name from cmd.exe.

for the source code see below

/*

* Program for reading a command prompt output from java

* Copyright 2009 @ yuvadeveloper

* Code By:- Prashant Chandrakar

*

*/

import java.io.*;

public class cmdReader

{

public static void main(String arg[])

{

new test().setup();

}

void setup()

{

System.out.println("Testing getVolName");

////drive which name to be read

String path = "D:";

System.out.println("Volume name for " + path + " is: " + "'" + getDiskVolumeName(path) + "'");

}

public static String getDiskVolumeName(String path)

{

String volname = "Unknown";

String check = "Volume in drive " + path.charAt(0) + " is ";

try

{

//creating a process object and calling a cmd.exe with /c dir option

Process p = Runtime.getRuntime().exec("cmd /c dir " + path);

//getting input stream from a process

InputStreamReader is = new InputStreamReader(p.getInputStream());

//creating a buffered reader object for reading purpose

BufferedReader reader = new BufferedReader(is);

///reading a line

String line = reader.readLine();

while (line != null)

{

//getting substring for drive name

if (line.indexOf(check) != -1)

volname = line.substring(line.indexOf(check) + check.length());

line = reader.readLine();

}

}

catch (Exception e1)

{

System.out.println("Failure: " + e1.toString());

}

return volname;

}

}

Here below i am pointed the read text.

Snapshot:-

No comments:

Post a Comment