File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes A prompt command! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "A prompt command!" Watch "A prompt command!" New topic

A prompt command!

Bruno Frascino
Ranch Hand

Joined: Jul 22, 2003
Posts: 55
Hi there,
How to "call" a command like "net send host_name message" from a java application?!
Which class i must use?!

Peter Kristensson
Ranch Hand

Joined: Jul 02, 2001
Posts: 118
Look at the java.lang.Runtime class, more specifically the exec methods.
Bruno Frascino
Ranch Hand

Joined: Jul 22, 2003
Posts: 55
Thanks Peter!!

It's simple... let me show for the others buddies:
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Originally posted by BJack:
It's simple... let me show for the others buddies:

There is no need to catch NullPointerException here. I presume that its inclusion was prompted by the JDK javadoc, but careful reading of that javadoc reveals that NullPointerException cannot occur in the example, because exec() is being passed a literal String, which cannot be null. In fact, it is very rarely appropriate to catch NullPointerException, because it indicates a programming error, rather than a user error or system fault.
Second, and much more subtle, there are problems with Runtime.exec() for any command that might produce a significant amount of output on standard output or standard error streams. If the buffers for these streams fill up, the process that has been run with exec() will hang forever. Therefore, you often need to ensure that these buffers are drained, while the process is running; you may need additional thread(s) to do this. It's a real pain, but Sun refuses to acknowledge that it's a problem.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Dmitry Melnik
Ranch Hand

Joined: Dec 18, 2003
Posts: 328
This piece of code handles the console output generated by the executed command, and waits for it to complete
// ===========
Process p;
try {
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader (new InputStreamReader(p.getInputStream ()));
String s;
while ((s = br.readLine ())!= null){
System.out.println (s);
} catch (Exception ex) {
"Failed to execute the script (" + cmd + ") :\n" + ex.getMessage());
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
Please change your name to be compliant with JavaRanch's naming policy. It should not be obviously fictitious.
Your displayed name should be 2 separate names with more than 1 letter each. We really would prefer that you use your REAL name.
You can change your name: here.

"JavaRanch, where the deer and the Certified play" - David O'Meara
I agree. Here's the link:
subject: A prompt command!
It's not a secret anymore!