jump to navigation

Capture Console Output in Java January 10, 2010

Posted by ratheeshnarayanan in Uncategorized.
trackback

I have been working on a test automation project with Silk4J for the past one month. While working on this project I came across a scenario where I had to execute few commands (like ipconfig, net accounts etc.) from Java (Silk4J) and the result of those commands being executed had to be captured.  Here is the solution I had given to our development team. I hope this will help someone who might have similar requirements.

try {

//Put your command here..

Process p = Runtime.getRuntime().exec(“net accounts”);

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

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

StringBuffer output = new StringBuffer();StringBuffer error = new StringBuffer();

String line = null;

while ((line = stdInput.readLine()) != null) {

output.append(line+”\n”);

}

 while ((line = stdError.readLine()) != null) {

error.append(line+”\n”);

}

if(!”".equals(output.toString()))

{

System.out.println(“HERE IS THE STD -OUTPUT- OF THE COMMAND YOU HAD EXECUTED:\n\n”+

output.toString());

}

if(!”".equals(error.toString()))

{

System.out.println(“HERE IS THE STD -ERROR- (IF ANY) OF THE COMMAND YOU HAD EXECUTED:\n\n”+

error.toString());

}

}

catch (IOException e) {

 e.printStackTrace();

}

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.