views:

71

answers:

2

Is there a way to start a process in Java? in .Net this is done with for example:

system.diagnostics.process.start("processname");

Is there an equivalent in Java so I can then let the user find the application and then it would work for any OS.

Thanks

How does that work if I provide a file?

+5  A: 

See Runtime.exec() and the Process class. In its simplest form:

Process myProcess = Runtime.getRuntime().exec(command);
...

Note that you also need to read the process' output (eg: myProcess.getInputStream()) -- or the process will hang on some systems. This can be highly confusing the first time, and should be included in any introduction to these APIs. See James P.'s response for an example.

You might also want to look into the new ProcessBuilder class, which makes it easier to change environment variables and to invoke subprocesses :

Process myProcess = new ProcessBuilder(command, arg).start();
...
NullUserException
You also need to read the process's output -- p.getInputStream() -- or the process will hang on some systems. This can be highly confusing the first time, and should be included in any introduction to these APIs. See James P.'s response for an example.
Andy Thomas-Cramer
@Andy Thanks. I incorporated your comment into my answer if you don't mind.
NullUserException
what if the default media player is VLC and I want to for example open "somevideo.avi" and I want it to use the default application which is vlc?
Milo
@Milo: http://www.mkyong.com/java/open-browser-in-java-windows-or-linux/
James P.
+1  A: 

http://www.rgagnon.com/javadetails/java-0014.html

import java.io.*;
public class CmdExec {

  public static void main(String argv[]) {
    try {
      String line;
      Process p = Runtime.getRuntime().exec
        (System.getenv("windir") +"\\system32\\"+"tree.com /A");
      BufferedReader input =
        new BufferedReader
          (new InputStreamReader(p.getInputStream()));
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();
    }
    catch (Exception err) {
      err.printStackTrace();
    }
  }
}

You can get the local path using System properties or a similar approach.

http://download.oracle.com/javase/tutorial/essential/environment/sysprop.html

James P.
Note that you should use the `.exec(String[])` form of the method, not the single string `.exec(String)` form which *is not a command line processor* -- it simply splits on spaces. They give the same result for this example `tree.com /A` but are different if given, for example, a filename that has spaces in it.
Stephen P