Search code examples
javaprocess

Starting a process in Java?


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?


Solution

  • 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