1

How to execute Windows or Linux commands from a Java application?

I want to run dir command from Java application without a command prompt.

How can this be done?

3 Answers 3

7

well .. you could do it with

Runtime.getRuntime().exec("...")

but you really don't want to ..

if you want to get a list of files in a directory use the File api! something like file.listFiles()

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. I am just asked dir command i need to execute all type of commands like make directory and some mail server command etc can i use same Runtime class?
sure you can, just look at the linked api.. make sure to use the right methods.. so for example if you have multiple arguments make sure to pass a string array so you don't have to handle argument escaping yourself.. the returned Process class allows you to read the output / error stream from the started process, etc.
0

probably you may need to read output of executed app as well, if you need that

Process p = Runtime.getRuntime().exec("...");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine()) != null)
      System.out.println(line);

Comments

0

Just a note, dir is not an executable as such, but a command in the Windows command interpreter. To run dir, you would do Runtime.getRuntime().exec("cmd /C dir");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.