-
Run a dos command from a Java class
Hi!
I would like to know a simple routine or the java instructions to just
execute a dos command, like "dir" or "java classname" from a java class.
Regards,
Alex
-
Re: Run a dos command from a Java class
Did you tried Process class in java.lang?
You might need to struggle with it though!
-HTH
DP.
"Alex Omar Pagan Ortiz" <aortiz@dcti.com> wrote:
>
>
>Hi!
>
> I would like to know a simple routine or the java instructions to just
>execute a dos command, like "dir" or "java classname" from a java class.
>
>Regards,
>
>Alex
-
Re: Run a dos command from a Java class
Hi Alex,
As in the prev. replay mentioned use:
proc = Runtime.getRuntime().exec(String cmdline);
But beware of a nice pitfall which costs me days of debugging.
If you use exec() (at least with Windows NT) you are responsible
to read the stdout and stderr stream of the process you've started. If you
don not so your process will hang and appearantly never terminate. Following
the code I used to solve
this problem. Don't know if this is the most elegant or efficient method
but it works for me.
Just put the proc value you've got from exec() and put it into the following
method:
protected int showOutputAndWaitForProcEnd(Process proc) throws IOException
{
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
BufferedReader readIn = new BufferedReader(
new InputStreamReader(in));
BufferedReader readErr = new BufferedReader(
new InputStreamReader(err));
int b;
int exit = -1;
boolean bReady = false;
while (!bReady)
{
try
{
exit = proc.exitValue();
bReady = true;
}
catch (IllegalThreadStateException isex)
{
}
suckStreams(readIn,readErr);
}
readIn.close();
readErr.close();
return exit;
}
protected void suckStreams(BufferedReader readIn, BufferedReader readErr)
{
try
{
while (readIn.ready() || readErr.ready())
{
if (readIn.ready()) System.out.println(readIn.readLine());
if (readErr.ready())
System.err.println(readErr.readLine());
}
}
catch (IOException ex)
{
System.err.println("suckStreams: " + ex);
}
}
"Alex Omar Pagan Ortiz" <aortiz@dcti.com> wrote:
>
>
>Hi!
>
> I would like to know a simple routine or the java instructions to just
>execute a dos command, like "dir" or "java classname" from a java class.
>
>Regards,
>
>Alex
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks