Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How To run Commands like dir,cls,....in java

 
sandeep TA
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I want to know how to run commands in java which run in command prompt like dir,cls,cd,.............. Is there any method to do this.

Sandeep T.A
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is not relevant to SCJP so I'm moving it to Java In General (Beginner).
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use one of the exec() methods in the java.lang.Runtime class to execute native commands. However, this is consider a bad practice since you are breaking Java's multi-platform (i.e. write once, run anywhere) ability. You are much better doing anything you need to do using the Java language; for example use the methods in the java.io.File class to get a directory listing rather then dropping to a command line in order to run "dir". (Search the beginners and IO forums as the question on how to do this has been asked and answred many times.)

If for some reason (and it would have to be a good one) you find it necessary to use an exec() method, the best way to do so is to wrap it in a OS specific class which either implements an interface, or is a subclass of a super wrapper class. This way you can have such a wrapper class for any OS the application might run on.

Be sure to read the API documentation for on the Runtime class; there are several overloaded versions of the exec() method.

With those warnings in mind, here is an example:

Basic Syntax:

Full Example (without wrappers):

[ March 13, 2005: Message edited by: Mark Vedder ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use exec to run external programs, but the few examples you gave will probably not do what you want. There's no visible window, and you can't exec commands in the console window that started the application.

For DIR look into the File object. You can create a File with a directory name argument and get a list of OS files. There's not going to be a correlary to CD, I think.

In Windows there are some trick ways to do CLS in a console app with the old DOS ANSI.SYS driver. Let us know if that's what you had in mind and maybe somebody who's made it work will chime in.

Let us know your overall objective - what do you need your program to do? There may be better options than Java and exec.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic