Link to home
Start Free TrialLog in
Avatar of kibkid
kibkid

asked on

Running dos commands from Java

Hi guys can I even do this?
How can I run dos commands from a Java app.
For example I know I can open programs from java:

Runtime r = Runtime.getRuntime();
      Process p = null;
      try{
          p = r.exec("notepad");
      }
      catch(Exception e){};

But how can I run the'dir' command?

thanx guys
Avatar of Mick Barry
Mick Barry
Flag of Australia image

try:

r.exec("cmd /c dir");
Avatar of kibkid
kibkid

ASKER

thanx man it does seem to work since there is no Exception however how can i see the listing?
How can i see the result of dir?
Coz I don't see them.

Thanx for the examples however I couldn't get them I got an error while attempting to the them
Avatar of kibkid

ASKER

I did this:

cmd /c dir > test.txt

and it redirected the results to the file but is there a way to see it on the run screen?
thanx
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kibkid

ASKER

Hey man thanx a lot but you are way ahead of me in Java knowledge so your code wasn't really easy to get but thanx for everything now I got it to work with your help, this is what I did:


Runtime r = Runtime.getRuntime();
      Process p = null;
      try{
          p = r.exec("cmd /c dir");
          BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
          while(!(in.readLine()).equals(null)){
          System.out.println(in.readLine());   }
      }
      catch(Exception e){
      System.out.println(e);};


That code will miss every second line, try more like this:

String line = null;
while(null!=(line = in.readLine()))
{
      System.out.println(line);  
}
Avatar of kibkid

ASKER

oh ok, thanx man really appreciate it