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?
Process process = new ProcessBuilder("processname"). start();
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.
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.
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
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(); ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With