There are many ways to execute shell commands and print results in java I guess, the famous and the most used way is Runtime.getRuntime().exec you can find a good explanation for that from here. Coming to the point i am using the same way but little different! I use BufferedReader,InputStreamReader for simplicity and I can't make it much advanced. On the main event I have created a String where you put your command with the second event it executes the command and prints the result before I start I would like to give some credits to luismcosta.
So What's next? go try this and have fun..
Here is the full program as I said before there's String called command where you put your shell command in. I have already added a command to ping this blog.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//http://www.ultimateprogrammingtutorials.info
class sss {
public static void main(String[] args) {
final String command = "ping www.ultimateprogrammingtutorials.info";
try {
execute(command);
} catch (Exception error) {
error.printStackTrace();
}
}
private static void execute(String command)
throws IOException {
String printline;
java.lang.Process p = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((printline = input.readLine()) != null) {
System.out.println(printline);
}
input.close();
}
}
Here's the result I got :Pinging ghs.l.google.com [74.125.135.121] with 32 bytes of data: Reply from 74.125.135.121: bytes=32 time=81ms TTL=49 Reply from 74.125.135.121: bytes=32 time=82ms TTL=49 Reply from 74.125.135.121: bytes=32 time=79ms TTL=50 Reply from 74.125.135.121: bytes=32 time=80ms TTL=50 Ping statistics for 74.125.135.121: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 79ms, Maximum = 82ms, Average = 80msIt shows ghs.l.google.com because I host this blog on google.
So What's next? go try this and have fun..

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