aspose file tools*
The moose likes Java in General and the fly likes Runtime getRuntime() exec(String command)  - How does this work? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Runtime getRuntime() exec(String command)  - How does this work?" Watch "Runtime getRuntime() exec(String command)  - How does this work?" New topic
Author

Runtime getRuntime() exec(String command) - How does this work?

Warren Bell
Ranch Hand

Joined: Dec 20, 2000
Posts: 56
I am trying to run a windows command line program from a java app. I am using Runtime.getRuntime().exec(String command), but I can not seem to get it to work. Do I need to do something else or is there a better way.
Thanks,
Warren Bell
Netricks
warren@netricks.net
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
You probably need to be a little more specific. Maybe post some code. The key thing to remember when using Runtime.exec() is you must consume everything from the child process' input stream.
[ June 16, 2003: Message edited by: Michael Morris ]

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Warren Bell
Ranch Hand

Joined: Dec 20, 2000
Posts: 56
Well let me rephrase my question. How do you run an external windows command line program from a java app.
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451

This just runs the dir command, captures its ouput and copies it to the programs stdout. Not very exciting but it shows the basic parts to use Runtime.exec(). You can also open up the process' output and error streams.
Warren Bell
Ranch Hand

Joined: Dec 20, 2000
Posts: 56
Thanks, I will try this and get back with you if I have any problems.
Warren Bell
Warren Bell
Ranch Hand

Joined: Dec 20, 2000
Posts: 56
Works like a charm, Thanks again.
Warren Bell
Saurav Chetia
Greenhorn

Joined: Oct 28, 2002
Posts: 10
Hi Michael !
Getting the output of the subprocess is working fine.
I am facing the problem of providing input to the subprocess. Please let me know how to do this.
I am posting a dummy code. To run the sample please replace 'somecommand' with a command which takes input.

Thanks
-Saurav
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Saurav,
Welcome to JavaRanch. If you are going to have both input and output you need to do each asynchronously. That is, you need to do each in a seperate thread. The Java bug parade is full of bug reports (which aren't actually bugs) regarding the input stream of a process filling up. When that happens your application hangs. See if you can do it yourself and if you get into trouble, post back and I'll give you some sample code.
Frank Hale
Ranch Hand

Joined: Mar 25, 2000
Posts: 230

Take for instance the code above. Why do we use the input stream to print the output? This is confusing me royally. Why wouldn't we use p.getOuputStream? Isn't that where the output of the command is?
I just can't figure out why we would use the input stream to get the commands output. Thats making no sense to me.
Please help me clarify it.
[ June 21, 2003: Message edited by: Frank Hale ]
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Well Frank, I can't speak for everyone but I have to stop and think about it too. I just remember that you always read from an input stream and write to an output stream. Try to think of a stream as a pipe with two ends. From the process' perspective the pipe is an output stream, but from the parent's point of view it is an input stream. The opposite is true for the process' output stream.
[ June 19, 2003: Message edited by: Michael Morris ]
Mir Ricco
Greenhorn

Joined: Jun 19, 2003
Posts: 15
Hi Michael,
thank you for redirection. This partly solve me my problem.
But how can I run another program, e.g. telnet or another java program by calling it like from command line. I tried to modify your first example to run telnet, but nothing happened.
Mir.
Mir Ricco
Greenhorn

Joined: Jun 19, 2003
Posts: 15
Is this topic described in details somewhere ?
Nilesh Nadiyana
Greenhorn

Joined: Dec 24, 2002
Posts: 21
You can invoke command line program(s) by saying:
Runtime rt = Runtime.getRuntime();
String[] cmd = new String[2];
cmd[0] = "cmd /c mkdir " + destDir;
rt.exec(cmd[0]);
Hope this helps. Let me know if I answered your question.
Nilesh Nadiyana
Greenhorn

Joined: Dec 24, 2002
Posts: 21
Also , you can invoke apps like notepad ;
Runtime rt = Runtime.getRuntime();
try {
rt.exec("notepad");
} catch (IOException ioe) {
ioe.printStackTrace();
}
Saurav Chetia
Greenhorn

Joined: Oct 28, 2002
Posts: 10
Hi Michael !
In my program I just want to execute one program (as subprocess) and provide it with some input. I am not doing both - providing input and getting output.
I used the code as posted earlier. However, the program just hangs :-(
From the API reference -
The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

Keeping this in mind I gave very small input. Still it hangs.
I tested the code on Windows NT 4 and Solaris 8.
I have not found any solution for this requirement. Is it feasible ? or is it one of the shortcomings of Java ? I'm sure there is some workaround for this which I have to figure out.
Thanks
-Saurav
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Here's a snippet from something I've been playing with off and on. I'll warn you it ain't perfect - it has some problems detecting when the command is done so it can disconnect all the streams. It starts the command, then pipes all the streams from the command to standard streams.

Now I left some things out as an exercise for the reader. The StreamConnector class is something I wrote that runs on its own thread and copies input from one stream out to another stream. The constructor parameters are input, descriptive name, output, and listener to notify when it is about to terminate.
My own non-standard variable name prefixes are a=argument, m=member.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
david chan
Ranch Hand

Joined: Jun 10, 2002
Posts: 46
sorry this is another question relate to runtime process exec command line, here is what I want to do: I mounted a network drive (win2k) to my win2k as G:\ drive, and I created a Web application run on tomcat, which will run any command line from the web page submited to: like this one:
cmd /c dir g:\
This will give me a "Access denied" error mesg,
but If I run "cmd /c dir c:\", I can see all my files and directory on C:\.
What's special for mounted driver?
Thanks.
David
david chan
Ranch Hand

Joined: Jun 10, 2002
Posts: 46
Ok, I think I know partially why. If I run the tomcat as services on win2k, it will give me the "Access denied" error mesg when try to access the mounted driver,
but if it is running from command prompt console, it is fine.
For the tomcat services, I tried to configure it log on as either local system or a specify user, both will give me Access denied error mesg.
Anyway, this seems not relate to runtime process, but if someone know how can I configure tomcat services, please let me know.
Thanks.
David
Andrew Reinartz
Greenhorn

Joined: Jul 02, 2003
Posts: 3
Can anyone help explain to me or point me to a link that explains the security issues when using Runtime.getRuntime.exec(etc.)?
I'm creating a GUI and remote access front-end applet for some files that are manipulated by a suite of optimized, C command-line programs. Eventually the command-line programs will be run on a remote server, but just for getting the interface up and running I want to be able to test it running the C programs from my own machine, but am getting security exceptions (saying access denied for exec on all files) because it's an applet. Also, the code works if I write it as just a normal command-lin class, not an applet, so I'm assuming it truly is a security issue.
Thanks in advance.
Vipin Kumar
Greenhorn

Joined: Jul 08, 2003
Posts: 1
Hi All,
Hi All,
The project which Iam currently working has a two tier architecture with Java at the front end and oracle at back end.We are using MSAccess for producing reports.Access is taking report data from Oracle using the link table functionality of Access.Currently the MS Access client is opened from Java Client.Then onwards operation is from MS Access only. Each reports prompts the user to put some parameter values.
Now my client is having a new requirement.They want to take the MS Access Reports directly from Java client.In java client , they will have a reports menu which will list all the reports available.On clicking the reports it will collect the parameter values which are required and pass to the access and the reports will be produced.
I have done above mentioned reqiurement using Java's runtime class.
code snippets are given below:
Runtime rt = Runtime.getRuntime();
String[]callAndArgs= {"D:\\applns\\Office2000\\Office\\Msaccess.exe","D:\\docs\\db7.mdb","/cmd","report1"};
rt.exec(callAndArgs);
The above code is works fine.But for each call new MSAccess process is creating.I want to use same process for accessing all the reports.Java's run time currently doesn't provide any API,by which I can get the complete control over the external process.Is any other way to sort out this issue??
Thanks in Advance....
Regards,
Vipin
Brian Joseph
Ranch Hand

Joined: May 16, 2003
Posts: 160
I found this, it covers the case where your process could lock up. It looks pretty good. The stdout and stderr is sent to a StringBuffer.
Thread On Runtime.exe blocking
[ July 11, 2003: Message edited by: Brian Joseph ]
Ajit Gupta
Greenhorn

Joined: May 03, 2004
Posts: 9
i have a problem while executing a c++ executable file frm my java code......if i use any other exe file other than one made by c++ ....it runs fine...but with c++ one it gives some environment error.....
so how do i run a c++ executable file frm my java code.....
Cesar Augusto De Leija
Greenhorn

Joined: May 18, 2004
Posts: 2
I am working in an applet and desire to execute from the applet a feasible program written in language C. Can you help with a fragment of I cosay me?


Please

Thanks
contact me
calg2@hotmail.com
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

No fragment, only two warnings:

Applets were meant to be published over the net to a remote computer.
Of course you may not know, if the programm (written in whatlanguage ever) is there - and where?

And applets run in the sandbox, so they aren't permitted to all the useful things, we normally want to do: write to disk, delete files, open connections to here and there, print, ...
You may sign your applet and grant it the rights to do all this - but normally you will run much easier, if creating an application without those restrictions. No signing needed.

There is an appletforum here too.


http://home.arcor.de/hirnstrom/bewerbung
Cesar Augusto De Leija
Greenhorn

Joined: May 18, 2004
Posts: 2
Thank you!!!
Dolly Jain
Greenhorn

Joined: Jun 09, 2004
Posts: 1
Hi All,
I would like to thank Nilesh for helping us in Using Runtime.getRuntime().exec() function in java.

I was facing the problem of invoking DOs command through Java.
I did the way Nilesh explained in his examples and my problem got resolved ..
Thanks again...
kalpana s
Greenhorn

Joined: Dec 22, 2003
Posts: 8
hi all,

i have a scaled down image on a jlabel. i hava a popup menu wiht a "preview"
menuitem. if i click on preview, i show be able to bring up mspaint.exe loaded with the image file - say a gif file using java.

how do i do this.

kalpana
Corey Hollaway
Greenhorn

Joined: Jul 21, 2004
Posts: 11
Originally posted by kalpana s:
hi all,

i have a scaled down image on a jlabel. i hava a popup menu wiht a "preview"
menuitem. if i click on preview, i show be able to bring up mspaint.exe loaded with the image file - say a gif file using java.

how do i do this.

kalpana


I'm totally new, but just so I feel special :
1) Save the picture to a temp folder

2) Open this baby in msPaint


I hope this helps!
Philippe Desrosiers
Ranch Hand

Joined: Mar 29, 2006
Posts: 138
Hi!

I'm having a problem calling Runtime.exec() under Linux. Some of the parameters I'm passing contain spaces. Normally, I would wrap these parameters in quotes, but for some reason, this doesn't work. Example:


What I want: above code should run mycmd, and pass the following parameters:
-param1
"here is some text"

What actually happens: the code runs mycmd, and passes the following parameters:
-param1
"here
is
some
text"

This causes my external command to barf, or to only process the first word of the quoted parameters.

This behavior is documented in Bug # 4365120 (here). This bug was closed without resolution.

Does anyone have any idea how I can work around this?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

Hi Phillippe,

Welcome to JavaRanch!

There's an overloaded version of Runtime.exec() that takes an array of Strings. Use that one instead, putting one "word" into each array element.


[Jess in Action][AskingGoodQuestions]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Wow, you really did search for an answer before posting! That was almost 2 years old.

In Java 5 and later look at ProcessBuilder. It offers a more intuitive way to build up your command and execute it. Or at least that's what it tries to do; let us know if it makes sense to you.
Upendra Chowdary
Greenhorn

Joined: Apr 21, 2006
Posts: 1
Hi,
Can any one send me some sample code to run an .exe file from java program. I want to enter input for that .exe file from java and also want to see the output corresponding to the output.

Yhanks in advance..

Upendra P
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41812
    
  62
Welcome to JavaRanch.

This article is a good starting point.


Ping & DNS - my free Android networking tools app
Gregory Nash
Greenhorn

Joined: Jun 09, 2006
Posts: 2
I'm wondering about internally managing Win32 applications. I've been trying to simplify my problem by internally managing notepad, but my real goal is to use WinZip with my java program.
I originally attempted to use the java.util.zip package to unzip files to a temporary folder but was unsuccessful. Currently I'm attempting to write a java program that uses WinZip to unzip files.
This problem arose because I'm writing a program that searches through a file system for particular files (ones that contain a keyword). I was able to search within a zip file using the java.util.zip package but my program gets stuck when it comes across a zip file within a zip file.
I'm excited about solving this problem because I imagine that the ability to internally manage Win32 applications would be a very useful tool for the future, but I'm worried that maybe java can only interact with a console I/O interface.
Please Help!
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18564
    
    8

Originally posted by Gregory Nash:
I originally attempted to use the java.util.zip package to unzip files to a temporary folder but was unsuccessful. Currently I'm attempting to write a java program that uses WinZip to unzip files.
That's the wrong response to your failure. Your fear is correct: trying to interface with Windows GUIs is hard enough in languages (like Visual Basic) which actually support that, and Java doesn't support it. The correct response is to use the java.util.zip package correctly. It's designed to do just what you want to do. Explaining your problem (in a new post) would be a good start.
Gregory Nash
Greenhorn

Joined: Jun 09, 2006
Posts: 2
Yeah, I figured out how to unzip with java.util.unzip by doing web searches before I read your reply but I was still curious if I could have done it with an external call to WinZip Thanks for satisfying my curiosity I feel better about not being able to do it now
Atanu Das
Greenhorn

Joined: Jun 30, 2008
Posts: 4
[ UD: Please DontWakeTheZombies. You already asked this question in another thread, where you were asked to provide more information. Let's continue the discussion over there. ]
[ July 01, 2008: Message edited by: Ulf Dittmer ]

Atanu Das<br />India
Sachin Telang
Greenhorn

Joined: Nov 02, 2007
Posts: 19
Very Nice thread and nice reply from all experts.Very informative.


Thanks<br />Sachin Telang<br />IBM Websphere Portal Application Developer Certified, Exam -399.
Sun Certified Java Programmer 1.5
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
Originally posted by Sachin Telang:
Very informative.
No, it isn't that informative, since nobody quoted the classic Daconta article about Threads to consume the Streams. It's here. Since this thread started the ThreadBuilder class was introduced which makes it a bit easier by combining the two input streams, but the system hasn't changed much.

And somebody else has been told not to resurrect 5-year old topics . . .

[edit]Mistake: I said ThreadBuilder; that's wrong. It should be ProcessBuilder. CR[/edit]
[ July 10, 2008: Message edited by: Campbell Ritchie ]
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41812
    
  62
Originally posted by Campbell Ritchie:
[QB]No, it isn't that informative, since nobody quoted the classic Daconta article about Threads to consume the Streams.


I didn't? Not on 4/21/2006?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Runtime getRuntime() exec(String command) - How does this work?