Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a process in Java?

Tags:

java

process

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?

like image 707
jmasterx Avatar asked Sep 22 '10 23:09

jmasterx


People also ask

How do you start a process in java?

Process process = new ProcessBuilder("processname"). start();

What is process execution in java?

The Process is an abstract class defined in the java. lang package that encapsulates the runtime information of a program in execution. The exec method invoked by the Runtime instance returns a reference to this class instance. There is an another way to create an instance of this class, through the ProcessBuilder.

What is process in java with example?

Process provides control of native processes started by ProcessBuilder. start and Runtime. exec. The class provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.


2 Answers

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

import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.file.Paths;  public class CmdExec {  public static void main(String args[]) {     try {         // enter code here          Process p = Runtime.getRuntime().exec(             Paths.get(System.getenv("windir"), "system32", "tree.com /A").toString()         );          // enter code here          try(BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {             String line;              while ((line = input.readLine()) != null) {                 System.out.println(line);             }         }      } 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

like image 79
James P. Avatar answered Oct 07 '22 00:10

James P.


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(); ... 
like image 21
NullUserException Avatar answered Oct 06 '22 23:10

NullUserException