Execute System Command using Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Execute System Command using Java

Share This

The following code shows, how to execute system commands using Java programming language. Using this sample code, a process is being created using runtime environment.

package com.t4b.test; import java.io.*; public class JavaRunCommand { public static void main(String args[]) { String s = null; try { Process p = Runtime.getRuntime().exec("ps -ef"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } System.out.println("Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } System.exit(0); } catch (IOException e) { System.out.println("exception happened - here's what I know: "); e.printStackTrace(); System.exit(-1); } } }

Happy Exploring!


Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.