Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to run a commandline command from a java program

 
Jyothsna Sri Y
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I wish to run a commandline command(eg: dir or cls) from my java program. How is this possible?
I also wish to run another exe file from my program. I have tried the following code:
Runtime r = Runtime.getRuntime();
Process p = r.exec("./rasmol");
But this doesn't seem to work, even if the exe is an excutable command from the commandprompt.
Thanks,
Regards
Jyothsna.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This doesn't actually have anything to do with threads; I'm going to recommend that it be moved.
First, as far as running rasmol goes: this code should work, given the right assumptions. Can you give any more details regarding what happens?
Second, as to running commands like dir or cls: both of these are built into the "cmd" or "command" shell on Windows (which you have depends on the Windows version, of course.) Therefore, you have to run "cmd" and tell it to run the command:

Now, note that that output from this process won't go to the terminal but to a Java InputStream that you can read from; get it using p.getInputStream().
Also, I doubt that running "cmd /c cls" is going to do anything, but it might surprise you.
 
Jyothsna Sri Y
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest,
Thanks a ton for the immediate response. I'm trying it.
But could you also tell me how I can run a .exe(executable from the commandline) file from my java program on linux.
cheers
Jyothsna.
 
Marilyn de Queiroz
Sheriff
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Java In General - Intermediate forum
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

But could you also tell me how I can run a .exe(executable from the commandline) file from my java program on linux.

The Java code is exactly the same as for Windows; you just have to name the appropriate executable (note that Linux executables don't end in ".exe".)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic