1

I'm trying to make a little java program that executes a system command but I can't seem to figure it out

The question is how does one execute a system command using java?

UPDATE: I read the documentation & tried some examples & I still can't figure it out. Why can't it be simple like in C.

omarello
  • 2,683
  • 1
  • 23
  • 23
Samantha Catania
  • 5,116
  • 5
  • 39
  • 69
  • possible duplicate of [How to call System commands from a java program](http://stackoverflow.com/questions/2693740/how-to-call-system-commands-from-a-java-program) – Mike Samuel Sep 03 '11 at 17:36
  • As I said in my answer, for simple cases it is indeed dirt simple. If you're trying to do something more complicated, perhaps you need to explain what that more complicated use case actually is? – Ernest Friedman-Hill Sep 03 '11 at 18:35

4 Answers4

4

You might want to have a look into the documentation for java.lang.ProcessBuilder. An example is given there.

Howard
  • 38,639
  • 9
  • 64
  • 83
2

Ultimately, you use the family of exec() methods in the java.lang.Runtime class. There's a class named java.lang.ProcessBuilder which helps in setting up a process to run, although you're not obligated to use it. Be sure to read this classic article on handling the input and output streams, running Windows CMD.EXE builtins, and other potential pitfalls.

Running a command can be as simple as saying

Runtime.exec("notepad");

but as that article points out, there are plenty of subtleties to worry about.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
2

Process Builder example

Srikanth Venkatesh
  • 2,812
  • 1
  • 20
  • 13
1

Apache Commons-Exec is similar to ProcessBuilder, but helps avoid a lot of common problems with the streams, process timeout, platform differences, etcetera. I recommend using that instead of ProcessBuilder.

Barend
  • 17,296
  • 2
  • 61
  • 80