Executing Linux command from Java

You know Linux commands are always fun. We always play on terminals. How about executing from our favorite language java?

Then you need following class


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CommandExecutor {
public static String execute(String command) {
StringBuilder sb = new StringBuilder();
String[] commands = new String[] { "/bin/sh", "-c", command };
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader input = new BufferedReader(new InputStreamReader(
proc.getInputStream()));

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

String s = null;
while ((s = input.readLine()) != null) {
sb.append(s);
sb.append("\n");
}

while ((s = stdError.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}

Now you can execute any command using this class.
For example-

public static void main(String[] args) {</pre>
String output = CommandExecutor.execute("ps aux | head -3");
 System.out.println(output);
 }

And output will in your console like:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  24600  2212 ?        Ss   Apr12   0:00 /sbin/init
root         2  0.0  0.0      0     0 ?        S    Apr12   0:00 [kthreadd]

Advertisements

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 )

Google+ photo

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

Connecting to %s