Execute external program (ping and complain)From WikiJavabuy this book
This example shows how to execute a shell command in Java and how to parse the output of the program. In this program I'll show you how to call the ping command. Basically calling any program should be the same story.
the article
I did this little program one day in which I had very bad internet connection in the office. The connection was down every now and then, leaving me waiting for long times, eventually just to see the timeout page. The program continuously pings a server which is on the net, and if the ping fails for a certain number of times, it uses the play wave sound to play a sound to advise me that the internet connection went down. The two key classes for this tutorial are java.lang.Process and java.lang.Runtime. The runtime class allows the application to interface with the environment in which the application is running. Using the method: Process java.lang.Runtime.exec(String command) throws IOException we can execute a command and obtain a java.lang.Process from it. At this point the command is running, we can get the output of it by simply attaching an java.io.BufferedReader.BufferedReader to the inputStream that we can obtain from the Process: in = new BufferedReader(new InputStreamReader(process .getInputStream()));
process.destroy(); Calling the destroy method should really be a 'just to be sure' procedure. The command should be already terminated when you call destroy. Forcing programs to be closed is never a good idea. In Ping and Complain for instance we call the destroy method only after the process has stopped generating output. Which in general could be considered a good indicator that the command is done. Code for executing the external programThis section contains a partial version of the program, download the complete source code from the SVN repository at: https://svn2.hosted-projects.com/wikijava/articles/dongiulio/SVN_LOCAL/org/wikijava/networking/ping/PingAndComplain.java like explained in the box above //The command to execute String pingCmd = "ping " + ip + " -t"; //get the runtime to execute the command Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(pingCmd); //Gets the inputstream to read the output of the command BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); //reads the outputs String inputLine = in.readLine(); int i = 0; int consecutiveFailures = 0; while ((inputLine != null)) { if (inputLine.length() > 0) { ........ } inputLine = in.readLine(); } playing the audio fileInputStream audioInputStream; try { audioInputStream = new FileInputStream(audioFileName); } catch (FileNotFoundException e1) { .... } PlaySound playSound = new PlaySound(audioInputStream); playSound.play(); See Also |

I've seen a discussion about this article on the Sun site. It lead to some debugging of this program.
--DonGiulio 01:29, 12 December 2008 (UTC)